jQuery .prop() method
A little introduction of the .prop() method is necessary, since we will use this method in our example to check or uncheck the checkboxes. The .prop(), that was introduced in the jQuery version 1.6, can check or uncheck a group of checkboxes in a container, with a single click of a button.
Denotes as property, the .prop() method is deemed faster than its predecessor .attr() or the attribute method. Prior to the release of version 1.6, attributes and properties were actually handled by the ‘.attr()’ method alone.
Anyways, speed does not matter in this case. All we want to do is check or uncheck the controls with a single stroke. And to accomplish this, we are using the ‘.prop()’ function.
First, we will add Google CDN for jQuery and later add a group of checkboxes in our markup section.
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script> <style> .grpCheck { color: #666; margin: 10px auto; } </style> </head> <body> <p>Click Select All to check or uncheck all checkboxes.</p> <div> <div class="grpCheck"> <input type="checkbox" />Excellent <br /> <input type="checkbox" />Good <br /> <input type="checkbox" />Fair <br /> <input type="checkbox"/>Poor <br /> <input type="checkbox"/>Not Applicable </div> <b><input type="checkbox" id="chkSelectAll" /><label id="sel">Select All</label></b> </div> </body> <script> $('#chkSelectAll').click(function() { if ($(this).is(':checked')) { $('.grpCheck> input[type=checkbox]').each(function() { $(this).prop("checked", true); $('#sel').text('Un-Select All'); }); } else { $('.grpCheck input[type=checkbox]').each(function() { $(this).prop("checked", false); $('#sel').text('Select All'); }); } }); </script> </html>
Browser Support:
Chrome 39.0 - Yes | FireFox 34.0 - Yes | Internet Explorer 8 and above - Yes | Safari - Yes