0

what I'd like is to be able to create an event listener for all and any check boxes in a document. Because check boxes and radio buttons will be added dynamically with JavaScript, rather then have a separate event listener for each one and just have a general event listener to check for changes in any checkbox with the jquery change function if that's possible of course. I know how to do this with one checkbox.

$('input[name=manybackgrounds]').change(function(){
if($(this).is(':checked'))
{
    alert("it is checked");
}
else
{
    alert("not checked");
}    

});

But since their could be an unpredictable amount of checkboxes, it would be easier to check if any have changes and then just ask which dynamically made ones are checked. Thank you in advance, greatly appreciate any help.

Alex
  • 132
  • 1
  • 1
  • 9

2 Answers2

0

The selector for all checkboxes is:

$('input[type=checkbox]')

Now do whatever you want with it!

Edit:

For dynamic checkboxes...

$(document).on('change', 'input[type=checkbox]', function(e) {
    //DO YOUR THANG
});

Read https://api.jquery.com/on/ for more info

Populus
  • 7,470
  • 3
  • 38
  • 54
0

As @JamesMontagne pointed out, you need to use event delegation. Make sure they are added in a container you can use, and then add the event handler on that container.

Supose you guarantee they are added in #container, you could do:

$("#container").on("click", "input[name=manybackgrounds]", function() { 
    if($(this).is(':checked'))
    {
        alert("it is checked");
    }
    else
    {
        alert("not checked");
    }    
});

src: http://api.jquery.com/on/

Miguel Hughes
  • 117
  • 12