Christian Gollhardt Christian Gollhardt - 4 months ago 13
Javascript Question

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

I want to have a button, to check or uncheck all checkbox.

This is my 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 this is my script:

$("#addAll").click(function() {
$("#container input:checkbox").attr('checked', 'checked');
});
$("#removeAll").click(function() {
$("#container input:checkbox").removeAttr('checked');
});


But it does not work as expected:


  • Check all, works

  • Uncheck all, works

  • Check all again, nothing happens



What could be the error?

See this fiddle

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

For the difference between .attr and .prop, please see this question: .prop() vs .attr()