Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

EventListener for checkboxes not working correctly

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading