Joshua Crocker Joshua Crocker - 4 months ago 14
jQuery Question

jQuery removeAttr blocks re-adding the attribute

I have a list of checkboxes that I want people to be able to tick individually, or bulk tick/untick for ease of use.

<input type="checkbox" name="category" id="c1" /> <label for="cl">Category</label>


The markup for the buttons to bulk tick/untick them is:

<p>
<a href="javascript:;" class="btn btn-info btn-xs" id="tick-all">Tick All</a>
<a href="javascript:;" class="btn btn-info btn-xs" id="untick-all">Un-Tick All</a>
</p>


and the JavaScript is:

$("#tick-all").click(function () {
$("input[type=checkbox]").attr('checked', 'checked');
});

$("#untick-all").click(function () {
$("input[type=checkbox]").removeAttr('checked');
});


but when I click the buttons in the order:
tick, untick, tick
, then they will only work the first two times, and after that, the checkboxes won't become ticked again.

Answer

Play around with prop() instead of attr

$("#tick-all").click(function () {
    $("input[type=checkbox]").prop('checked', true);
});

$("#untick-all").click(function () {
    $("input[type=checkbox]").prop('checked',false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="category" id="c1" /> <label for="cl">Category</label>
<input type="checkbox" name="category" id="c1" /> <label for="cl">Category</label>
<input type="checkbox" name="category" id="c1" /> <label for="cl">Category</label>
<p>
    <a href="javascript:;" class="btn btn-info btn-xs" id="tick-all">Tick All</a>
    <a href="javascript:;" class="btn btn-info btn-xs" id="untick-all">Un-Tick All</a>
</p>