JQuery to check and uncheck only works once

I have a very simple requirement for my jQuery: check the set of mailboxes if the switch is set, and clear them if another checkbox is selected.

Jquery works, however it only works once - that is, if I click to check them all (all checkboxes are checked), then click to clear them (all boxes are cleared), and then click again to check them all - there is no effect. Similarly, if I manually uncheck some boxes, then click to select all again, there is no effect.

JQuery

$('#all').on('change', function() { if (!$(this).is(':checked')) { $('.country').attr('checked', false); } else { $('.country').attr('checked', true); } }); $('#none').on('change', function() { if (!$(this).is(':checked')) { $('.country').attr('checked', true); } else { $('.country').attr('checked', false); } }); 

HTML

  <div class="subselect"> <input type="radio" class="TLO" name="radio1" id="all" />Check All <br /> <input type="radio" class="TLO" name="radio1" id="none" />Clear All <br /> </div> <br /> <br /> <div class="cselect" id="countries"> <input type="checkbox" class="country" />1 <br /> <input type="checkbox" class="country" />2 <br /> <input type="checkbox" class="country" />3 </div> 

jsFiddle http://jsfiddle.net/vsGtF/1/

+7
source share
2 answers

Change .attr() to .prop() .

 $('#all').on('change', function() { if (!$(this).is(':checked')) { $('.country').prop('checked', false); } else { $('.country').prop('checked', true); } }); $('#none').on('change', function() { if (!$(this).is(':checked')) { $('.country').prop('checked', true); } else { $('.country').prop('checked', false); } }); 

JsFiddle example

You can also reduce this by simply:

 $('#all').on('change', function () { $('.country').prop('checked', $(this).is(':checked')); }); $('#none').on('change', function () { $('.country').prop('checked', !$(this).is(':checked')); }); 

JsFiddle example

Like docs for .attr () state:

As in jQuery 1.6, the .attr () method returns undefined for attributes that have not been set. To get and change DOM properties, such as the checked, selected, or disabled state of form elements, use .prop ().

+29
source

I know that there was a lot of deceit, but I missed something, I had:

 id = $(this).attr('id'); if($('#checkbox_' + id).prop('checked')){ $('#checkbox_' + id).attr('checked', false); } else { $('#checkbox_' + id).attr('checked', true); } 

And, as mentioned above, ALL attr cases need to be replaced for prop ()

 if($('#checkbox_' + id).prop('checked')){ $('#checkbox_' + id).prop('checked', false); } else { $('#checkbox_' + id).prop('checked', true); } 

Hope someone helps ...

+2
source

All Articles