Skip to content Skip to sidebar Skip to footer

Select All Check Boxes Using Button

I have HTML page which have multiple check boxes and individually they can be checked. I have button select, so what I am suppose to do is. When I click on select all the check box

Solution 1:

$(document).ready(function () {
  $('body').on('click', '#selectAll', function () {
    if ($(this).hasClass('allChecked')) {
        $('input[type="checkbox"]', '#example').prop('checked', false);
    } else {
        $('input[type="checkbox"]', '#example').prop('checked', true);
    }
    $(this).toggleClass('allChecked');
  })
});

Example on jsFiddle

This will add a class, allChecked, on the "Select All" button when all items have been checked (and remove it when all are unchecked). Also, it will only look within the #example (your table with id example) context. This can be tweaked to your liking of course, as with anything.

Edit:

And to make sure that your jQuery is loaded. Try this script tag instead (replace your current):

<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

Edit: Just updated the syntax in fiddle for <table> tag as it was not the self closing tag

Solution 2:

You can try this:

$('#selectAll').click(function(e){
    $(this).toggleClass('clicked');
    $(this).closest('table').find('input[type="checkbox"]').prop('checked', $(this).hasClass('clicked'))
});

In this code what happening is:

  1. First you bind the click on the button.
  2. After click toggle a dummy classname to the button.
  3. Then traverse up the the table and find all the checkboxes.
  4. then change the property checked to true/false which depends on the class added to the button.

Solution 3:

Try this

Demo

$("#selectAll").on("click", function () {
    $("#example tr").each( function() {
             $(this).find("input").attr('checked', true);             
    });
});

Solution 4:

Post a Comment for "Select All Check Boxes Using Button"