Hello-World
Hello-World

Reputation: 9555

check all and uncheck all check boxes

I need to be able to click on the button btn and select all check boxes, then click on it again and it will uncheck all. but my code below will only check all and uncheck all once. why does it stop working?

<script>
$('document').ready(function(){
$("#btn").on("click", function () { 
       var $checkbox = $(".checkBoxClass");
       $checkbox.attr('checked', !$checkbox.attr('checked'));
 });
});

</script>
 <span id="btn">btn</span><br /><br />
        <input type="checkbox" class="checkBoxClass" id="Checkbox1" />
        <br />
        <input type="checkbox" class="checkBoxClass" id="Checkbox2" />
        <br />
        <input type="checkbox" class="checkBoxClass" id="Checkbox3" />
        <br />
        <input type="checkbox" class="checkBoxClass" id="Checkbox4" />
        <br />
        <input type="checkbox" class="checkBoxClass" id="Checkbox5" />
        <br />

Upvotes: 1

Views: 360

Answers (2)

Dan Lister
Dan Lister

Reputation: 2583

What about...

$('#btn').on('click', function() {
    $('.checkBoxClass').each(function() {
        $(this).is(':checked') ? $(this).removeAttr('checked') : $(this).attr('checked','checked');
    });
});

Upvotes: 1

Liam
Liam

Reputation: 29760

what do you expect !$checkbox.attr('checked') to return? Because $checkbox.attr('checked') returns 'checked' or nothing.

You should use prop not attr for this as it's truey/falsy

$('document').ready(function(){
   $("#btn").on("click", function () { 
       var $checkbox = $(".checkBoxClass");
       $checkbox.prop('checked', !$checkbox.prop('checked'));
    });
});

so now !$checkbox.prop('checked') returns true or false which you can legitimately call ! against

Upvotes: 6

Related Questions