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/
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.
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() {
...
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With