1

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");
                }
            });


});


bipbip
  • 37
  • 5

1 Answers1

2

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'/>
Negi Rox
  • 3,364
  • 1
  • 8
  • 15
  • in load function i build multiple checkbox. in ready function i would like to click on it to launch a function – bipbip Nov 19 '19 at 14:46
  • It's ok i understand : $("#idcheckbox").on("click", "input[type='checkbox']", function () { if ($("input[type='checkbox']").is(':checked')) { alert("jQuery checked"); } else { alert("jQuery no checked"); } }); – bipbip Nov 19 '19 at 15:28