The problem you're having is that your input isn't on the page when you hook up your event. As a result, it doesn't work.
As you noted, one way to fix the problem is to use live
. What live
does is add an event handler to the document body itself. Then, when any event from your input "bubbles up" to the body event handler, it handles it. This way even if the input isn't on the page when you add the event handler it still works (because the body is on the page).
But there's a problem: as others have noted, live
is deprecated. The reason for this is simple: if you use live
a lot (or even a medium amount) it can cause huge performance problems, because every event on your page has to go through every event handler you put on the body.
The solution is not to use live, but not to do what you're currently doing either. Instead, you simply want to hook up your event handler:
$("input[name='child_user_id_fk[]']").change(function(){
alert("test");
$(this).closest("tr").toggleClass("checked", this.checked);
});
AFTER you add your input to the page. For instance:
$('body').append('<input name="child_user_id_fk[]" />');
$("input[name='child_user_id_fk[]']").change(function(){
alert("test");
$(this).closest("tr").toggleClass("checked", this.checked);
});
Or to simplify it with chaining:
$('body').append('<input name="child_user_id_fk[]" />')
.change(function(){
alert("test");
$(this).closest("tr").toggleClass("checked", this.checked);
});
As long as you hook up the event handler to an element that's in the DOM (ie. as long as you do the change
after you do your append
, or html
, or however you add the element) it will work.
EDIT
As noted in a comment you could also use on
. However, on
will also require the element to be on the page, unless your target for the on
is the body itself (in which case you're basically just using on
to do the same thing as live
).