简体   繁体   中英

Event doesn't work when element isn't loaded directly

I have a table with many checkboxes which is generated with Ajax :

$.ajax({
    type: "GET",
    url: "jsonDevisUtilisateur.php?ra=" + $('#ra').val(),
    success: function(data) {
        var table = "<table class='dvs'><tr><td>Numéro</td><td>Client</td><td>Site</td><td>Libellé</td><td>Statut</td><td></td></tr>"
        for (var i = 0; i < data.length; i++) {
            table += "<tr><td>" + data[i].numDevis + "</td>";
            table += "<td>" + data[i].client + "</td>";
            table += "<td>" + data[i].site + "</td>";
            table += "<td>" + data[i].libelle + "</td>";
            table += "<td>" + data[i].statut + "</td>";
            table += "<td><input type='checkbox' class='box' value='" + data[i].id + "' name='box[]'></td></tr>"
        }
        table += "</table>";
        document.getElementById('devis').innerHTML = table + "<br/><br/>";
    }
});

This part is working well ! The problem is when I'm trying to integrate a "select all" button.

My Javascript for it :

$(document).ready(function() {
    $("#selectall").on("change", function(e) {
        $("input[type=checkbox]").prop("checked", $(this).prop("checked"));
    });
});

When my select all checkbox : <input type='checkbox' id='selectall' name='selectall'> is created on the same time than my HTML, it works.

But if I create my <input type='checkbox' id='selectall' name='selectall'> in my TABLE with my ajax function, it doesn't work, and nothing happens.

I'm pretty sure it is because the event is set to "selectall" at the load of the page but it doesn't exist yet and it doesn't look for it later.

What would be the solution ? Thanks for help

You can use event delegation as follow:

$('#devis').on("change", "#selectall", function(e) {
    $("input[type=checkbox]").prop("checked", $(this).prop("checked"));
});

You are right in your thinking :

If your selectall checkbox is created after the document ready code execution, jquery can't find it (as it's not created yet).

I won't recommand using the live function as it is deprecated and can be removed in futur version of jquery.

You can still use the on function but with a little modification :

$("#devis").on("change", "#selectall",function(e) {

Note that #mycontainer MUST exist on document load.

If you can't place a container, this will always work :

$("body").on("change", "#selectall",function(e) {

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