I have a form which contains a set of checkboxes where multiple selection is possible. (Code snippets below).
The form's inner HTML is added by AJAX due to the time it takes to generate the contents, so the user initially sees a blank form and a few seconds later, its contents.
The problem is that the checkboxes need an onchange()
event. For static fields that's easy - I would probably give them all the same class, then use jQuery $(".mychkboxes").on("change", my_event_handler);
For dynamically added fields I gather from other questions I would need to use event delegation, which I'm not so confident about, so I've added an onchange="my_event_handler();"
to the field definition in the AJAX handler, and of course the handler function already exists in the web page in the browser when the form is populated.
But what's happening is that if I do "onchange=\"alert('test'); my_event_handler();\" "
, the alert fires, so I know it's working, but my_event_handler()
is never called although it exists and wasn't added programmatically.
I can't figure out why. Alternatively how would I add the handler programmatically in jQuery, so I can compare the 2 approaches.
Relevant Javascript (using events.push
due to other reasons, in case relevant):
<script type="text/javascript">
//<![CDATA[
events.push(function() {
function my_event_handler() {
alert("handler entered");
}
... ajax success handler relevant line...
$('#myform_div').html(data.form_html);
});
//]]>
</script>
data.form_html
includes this snippet (obviously the handler call here wouldn't be needed if done programmatically via delegation):
<div id="mydiv">
<input class="chk_mycheckboxlist" name="chk_mycheckboxlist[]" onchange="alert('event triggered'); my_event_handler();" id="chk_mycheckboxlist_item998" type="checkbox" value="998">
...
<input class="chk_mycheckboxlist" name="chk_mycheckboxlist[]" onchange="alert('event triggered'); my_event_handler();" id="chk_mycheckboxlist_item999" type="checkbox" value="999">
</div>