Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic checkbox onchange & javascript

This might be an easy one for you, but I'm stuck, so I hope you can help me.

I'm creating checkboxes through a loop and want to specify a text somewhere in the website if a checkbox is clicked.

I'v seen solutions where a make a script for each checkbox, but that could turn out to be alot sometimes (something like this: chckbx.onchange = function(){} )

I'd rather have one function that is called from different checkboxes, but my javascript skills is basicly non-existing :)

This is what i got so far (which ofcourse dosn't work) http://jsfiddle.net/Sz3BK/130/

like image 590
Rosenthaler Avatar asked Jan 11 '23 17:01

Rosenthaler


2 Answers

You have jQuery tagged in your question, so I'm going to provide a jQuery answer:

You'd use jQuery's on() method to delegate the event to a non-dynamic ancestor of your checkbox:

$('elem').on('change', 'input[type="checkbox"]', function() {
    ...
});

Where elem is a non-dynamic ancestor of your checkbox.

In your JSFiddle your checkbox isn't dynamic, but assuming it was, the closest non-dynamic ancestor of it would be the document's body. Therefore, we can use:

$('body').on('change', 'input[type="checkbox"]', function() {
    testing('hello', '1');
});

JSFiddle demo.

You may want to extend this by passing in "hello" and "1" as data-* attributes:

<input type="checkbox" name="test" data-newvalue="hello" data-spanid="1" />
<input type="checkbox" name="test" data-newvalue="second" data-spanid="2" />

Here I've created two checkboxes with our two data-* attributes. In our jQuery method we can pull these values and pass them into our testing() function using jQuery's data() method:

$('body').on('change', 'input[type="checkbox"]', function() {
    testing($(this).data('newvalue'), $(this).data('spanid'));
});

JSFiddle demo.

We can then modify our testing() function to also use jQuery:

function testing(newValue, spanID) {
    $('#'+spanID).text(newValue);
}

This pulls our spanID (e.g. "1") and places it within an ID selector $('#1'), then modifies the text using jQuery's text() method. If you wanted to modify the HTML instead, jQuery also has a html() method for this purpose.

Final JSFiddle demo.

like image 189
James Donnelly Avatar answered Jan 22 '23 08:01

James Donnelly


because you are adding che checkboxes dynamicly, to enable the change event for those added later, use code below

    $(document).on('change', 'input[type="checkbox"]', function() {
    ...
    });
like image 26
reZa Avatar answered Jan 22 '23 07:01

reZa