Write jQuery code for a “select all” checkbox

Description: A master checkbox must check or uncheck all the item checkboxes. If one item is unchecked, the master must be unchecked.

Hint:

  • Use .prop('checked', ...) and compare the count of all and checked boxes.

HTML of the page

<input type="checkbox" id="all"> Select all
<input type="checkbox" class="item"> A
<input type="checkbox" class="item"> B
<input type="checkbox" class="item"> C

Solution

$('#all').on('change', function () {
  $('.item').prop('checked', this.checked);
});

$('.item').on('change', function () {
  var allChecked = $('.item:checked').length === $('.item').length;
  $('#all').prop('checked', allChecked);
});

$('#all').prop('checked', true).trigger('change');
console.log('checked items: ' + $('.item:checked').length);

$('.item').eq(1).prop('checked', false).trigger('change');
console.log('master checked: ' + $('#all').prop('checked'));
Console output

checked items: 3
master checked: false

How it works

  • The master sets the checked property of all items.
  • When one item changes, we compare the number of checked items with the total.

Read Get Content (attr vs prop).


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.