why is my checkbox.change not working (jquery)?

Dird picture Dird · Sep 8, 2014 · Viewed 29.3k times · Source

I've done similar things before, click a checkbox then do something (.parent() etc) but for some reason it's not registering this time. Can anyone see why?

$.each( email_list, function( key, value ) {
$("#email_span").after("<tr><td><input type='checkbox' name='member' checked='checked' onclick='check_change(this);' /></td><td>" + value.name + "</td><td>" + value.email + "</td></tr>");
$("#emails").prepend(value.email + ";");
});

$('.member').change(function() {
   alert ("FECK");
   if(this.checked) {
   }
});

It is all within the $(document).ready block. I've got it working with a function call but was curious why the jQuery .change wasn't working?

Answer

Irvin Dominin picture Irvin Dominin · Sep 8, 2014

For dynamically created element you have to use event delegation, if you want to select by an attribute you can use an attribute equals selector.

Code:

$(document).on("change", "input[name='member']", function () {
    alert("FECK");
    if (this.checked) {}
});

Demo: http://jsfiddle.net/2fepaf0y/