javascript - How to create "check/uncheck all" with checkboxes? -


this question has answer here:

i want have button, check or uncheck checkbox.

this markup:

<div id="container">   <input type="checkbox">   <input type="checkbox">   <input type="checkbox">   <input type="checkbox"> </div> <button type="button" id="addall">add all</button> <button type="button" id="removeall">remove all</button> 

and script:

$("#addall").click(function() {   $("#container input:checkbox").attr('checked', 'checked'); }); $("#removeall").click(function() {   $("#container input:checkbox").removeattr('checked'); }); 

but not work expected:

  • check all, works
  • uncheck all, works
  • check again, nothing happens

what error?

see this fiddle

$("#addall").click(function() {   $("#container input:checkbox").prop('checked', true); }); $("#removeall").click(function() {   $("#container input:checkbox").prop('checked',false); }); 

this bug in jquery, because using native setattribute , removeattribute works fine.

https://jsfiddle.net/jz5p57k9/


have opened bug jquery team, can follow here: https://github.com/jquery/jquery/issues/3242#issuecomment-234315378

for difference between .attr , .prop, please see question: .prop() vs .attr()


Comments