EventListener for checkboxes not working correctly

Issue

I have a lot of checkboxes are created through this loop, and I want that when one is clicked, the words "Not Showing, " turn to "Showing." I’m using object.on(), here object is my class for my table, but when I click on a checkbox, not only does the checkbox not check, but it continually fires this function and no words change, instead it just console.logs "Clicked" hundreds of times. Then the program breaks. Anybody know why? Thank you.

    data.forEach((row) => {
      myTable += "<tr>" + "<td>" + `<label id="label" ><input type="checkbox"><span> Not showing</span></label>` + "</td>"+ "<td>" + row.name + "</td>" + "<td>" + app.nations[row.nation] + "</td></tr>"
      $('.table-sticky-container').on('click', 'label', function() {
        console.log("Clicked");
        var checked = $('input').is(':checked');
        $('span').text(checked ? ' Showing' : ' Not showing');
      });
    });

Solution

The issue is that you’re creating a new listener on ALL .table-sticky-container every time you iterate your loop. On top of which you’re telling jQuery to check all input elements to see if they’re checked.

What you should do is put your event delegate outside the loop and use relative paths for your logic, like this

// set the delegate
$('.table-sticky-container').on('click','label', function() {
    let txt = $(this).find('input[type=checkbox]').prop('checked') ? "Showing" : "Not showing";
    $(this).find('span').html(txt);
})

Answered By – Kinglish

Answer Checked By – Gilberto Lyons (AngularFixing Admin)

Leave a Reply

Your email address will not be published.