0

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

Christian Gollhardt
  • 16,510
  • 17
  • 74
  • 111
  • @CBroe there seems no other question on SO that points to this issue. May be the accepted answer is duplicate, but this question doesnt deserve to be flagged. – rishabh dev Jul 21 '16 at 17:18

1 Answers1

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

This is probably a bug in jquery, because using native setAttribute and removeAttribute works fine.

https://jsfiddle.net/jz5p57k9/


I have opened a bug for Jquery team, you can follow it here: https://github.com/jquery/jquery/issues/3242#issuecomment-234315378

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

Community
  • 1
  • 1
rishabh dev
  • 1,711
  • 1
  • 15
  • 26