jqueryjquery-click-eventjquery-onjquery-attributes

jQuery .on() click runs correctly only once


I have created following small code to replicate the problem I am actually facing. When I click on "Select All" button for the first time it works fine. Similarly when i click on "Select None" button it works fine. But when I click "Select All" again it doesn't work. Similarly if I .empty() the div and repopulate it with "Click Me" button. Both buttons work for the first time only. My jQuery code is as follows:

$("#populate").click(function() {
   $("#populateme").empty();
   $("#populateme").html("<input type=checkbox name=tester1 class=tester value=1><input    type=checkbox name=tester2 class=tester value=2><input type=checkbox name=tester2  class=tester value=3><input type=button name=selectall id=selectall value=selectall><input  type=button name=selectnone id=selectnone value=selectnone>");
});
$(document).on("click","#selectall",function() {
   $(".tester").attr("checked",true);
});
$(document).on("click","#selectnone",function() {
   $(".tester").attr("checked",false);
});

You can preview the problem on the following link: http://jsfiddle.net/RHFMT/1/


Solution

  • Use prop instead of attr to set and clear the checked state, like this:

    $(document).on("click","#selectall",function() {
        $(".tester").prop("checked",true);
    });
    $(document).on("click","#selectnone",function() {
        $(".tester").prop("checked",false);
    });
    

    See more details here: Setting "checked" for a checkbox with jQuery?