0

I want to use Jquery to reset checkboxes. I've read the Q/A on the topic and came up with this:

<script>
$(document).ready(function(){
    $("#clearall").click(function(){
        alert('clearing checkboxes');
        $('input:checkbox').attr('checked',false);
    });
});
</script>
<input id="cb1" type="checkbox" checked>
<input id="cb2" type="checkbox" checked >
<button id="clearall">Click me</button>

On load, two checkboxes appear checked. Clicking the button clears them. This is as expected. What is NOT expected is that if I check the boxes and click the button, the check boxes do NOT clear. No javascript errors or warnings appear. I've checked the functionality in Firefox, Safari and Chrome - and all 3 operate the same way. I inserted an alert which fires on every attempt, so the function is executing - but the checkboxes aren't getting reset after the first time. Can anyone offer any insight into why the check boxes do NOT clear if set by the user?

2 Answers2

0

Tip: when dealing with boolean attributes (such as disabled, checked, selected, etc.), use .prop() and never use .attr(), .removeProp(), or .removeAttr(). Why? This is because this and this.

  • .attr() and .removeAttr(): properties are dynamic and attributes are not--they reflect the initial value.
  • .removeProp():

    Note: Do not use removeProp() to remove native properties such as checked, disabled, or selected. This will remove the property completely and, once removed, cannot be added again to element.

$(document).ready(function(){
    $("#clearall").click(function(){
        $('input:checkbox').prop('checked',false);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="cb1" type="checkbox" checked>
<input id="cb2" type="checkbox" checked >
<button id="clearall">Click me</button>
Community
  • 1
  • 1
Terry
  • 63,248
  • 15
  • 96
  • 118
  • @user7491506 Do you really want me to google that for you? http://stackoverflow.com/questions/6169826/propchecked-false-or-removeattrchecked and http://ejohn.org/blog/jquery-16-and-attr/ – Terry Mar 21 '17 at 13:29
0

Try using .removeAttr('checked')

user7491506
  • 186
  • 1
  • 3