Henk Ertje Henk Ertje - 1 month ago 5
jQuery Question

Convert document ready to on jQuery

I'm trying to convert this document to

on()
but I don't know how. This is my code:

$(document).ready(function() {
var $sub = $("#removImg").hide(),
$chnckbox = $('input[name="chkboxplat[]"]').click(function() {
$#sub.toggle( $chnckbox.is(":checked") );
});
});


I tried
$(document).on(function(){
. Hope you can help me, thanks!

Answer

From the description of the issue in your comment you need to use a delegated event handler on the checkbox as it's dynamically appended to the DOM.

To do this you do need to use on(), however the syntax you had was incorrect. You need to add a new event handler, not replace the document.ready handler. Try this:

$(document).ready(function() {
    var $sub = $("#removImg").hide();

    $(document).on('change', 'input[name="chkboxplat[]"]', function() {
        $sub.toggle(this.checked);
    });
});

Note the use of the change event, not click, so that the code works for users who navigate via the keyboard