0

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.

1
  • 1
    Use .prop('checked', true); and .prop('checked', false); Commented Aug 9, 2016 at 12:11

3 Answers 3

1

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>

Sign up to request clarification or add additional context in comments.

Comments

1

Use

$("input[type=checkbox]").attr('checked', true);
$("input[type=checkbox]").attr('checked', false);

or

$("input[type=checkbox]").prop('checked', true);
$("input[type=checkbox]").prop('checked', false);

Comments

1

User Jquery Prop method like below

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.