TheAmazingKnight
TheAmazingKnight

Reputation: 2474

How to trigger check all checkboxes?

I'm trying to figure out how to trigger a link button to trigger and change all checkboxes to checked when clicked upon. When I click the button, it will bring up the alert message, but not triggering the checkboxes. I've tried some answers listed in this site, but it doesn't work. I recreated the problem with a jsfiddle.

HTML:

<h3><a href="javascript:void(0);" id="checkAll">Check</a> All</h3>
<hr/>
<input class="categories" type="checkbox" name="filter" value="Math" checked>Math<br/>
<input class="categories" type="checkbox" name="filter" value="Science" checked>Science<br/>
<input class="categories" type="checkbox" name="filter" value="Reading" checked>Reading

JS:

$('#checkAll').click(function()
{
  alert("checkAll was clicked!");
  console.log("Checkboxes has been refilled!");
  $(':checkbox.categories').prop('checked', $(this).checked); // re-check all checkboxes
  //$("input:checkbox").prop('checked', $(this).prop("checked"));
});

Upvotes: 2

Views: 385

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337627

The issue is because this will refer to the a element and the jQuery object containing that element has no checked property. Instead, just set it to true:

$('#checkAll').click(function(e) {
  e.preventDefault();
  $(':checkbox.categories').prop('checked', true);
});

Updated fiddle

Upvotes: 6

Related Questions