简体   繁体   中英

jQuery:click function() ready doesn't work after the load function

In jQuery 3.2.1 if I build checkbox after the load function, the click function doesn't work when I click the checkbox.

If I build the checkbox before for testing, it works!

How can I code it so the click function works after dynamically building the checkbox in the load function?

<div id="idcheckbox">
</div>


$(window).on('load', function () {
      $("#idcheckbox").append("<div class='custom-control custom-checkbox custom-control-inline'><input type='checkbox' class='custom-control-input' id=" + identifiant + " value=" + url + "><label class='custom-control-label' for=" + identifiant + ">" + url + "</label></div>");
});

$(document).ready(function () {

     $("input[type='checkbox']").on('change', function () {
                alert("0000");
            });

     $("input[type='checkbox']").on('click', function () {
                alert("1111");
            });

     //solution 
     $("#idcheckbox").on("click", "input[type='checkbox']", function () {
                if ($("input[type='checkbox']").is(':checked')) {
                    alert("jQuery checked");
                } else {
                    alert("jQuery no checked");
                }
            });


});


You are binding event on document.ready and then you are building control on window.load so it will not work because event is already bind with existing control. if you are making new control you need to add it after adding control to DOM.

 var identifiant = "dynamic", url = "www.google.com"; var counter = 1; $(window).on('load', function() { dynamicControl(); }); function dynamicControl() { var id = identifiant + counter; $("#idcheckbox").append("<div class='custom-control custom-checkbox custom-control-inline'><input type='checkbox' class='custom-control-input' id=" + id + " value=" + url + "><label class='custom-control-label' for=" + id + ">" + url + "</label></div>"); $("#" + id).on('change', function() { alert('dynamic alert') }); counter++; } $(document).ready(function() { $("input[type='checkbox']").on('change', function() { alert("0000"); }); $("input[type='checkbox']").on('click', function() { alert("1111"); }); $("#Dynamic").on('click', dynamicControl); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="idcheckbox"> </div> <input type='button' id='Dynamic' value='Add new checkbox'/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM