Thursday, September 5, 2013

Select and deselect all checkbox using jQuery



Select and deselect all checkbox using jQuery:
First link to jQuery library
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
Create a checkbox with id selectall to select all:
<input type="checkbox" id="selectall">Select all</input><br />
Create three checkboxs with class selectId
  <input type="checkbox" class="selectedId" name="selectedId" id="1" />1 <br />
<input type="checkbox" class="selectedId" name="selectedId" id="2" />2 <br />
<input type="checkbox" class="selectedId" name="selectedId" id="3" />3 <br />
iQuery code:  $(this).is(":checked") is the same as $(#selectall).is(":checked"), which return true when the slect all checkbox is checked, else false.  Set the attribute of  class selectedId for checkbox
the same as  select all.
<script>
 $('#selectall').on('click', function() {
    $('.selectedId').attr('checked',$(this).is(":checked"));
});
 </script>
 Demo: put all these together, check Select all, 1,2,3 are checked, un-check Select all, 1,2,3 are unchecked.
Select all
1
2
3
This code only works for the first and second, but failed for third click for selectall check box after.
Better code: work for any click for selectall  checkbox
 <html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js">
</script>
<script>

function selectAll(status) {
   $('input[name=selectedId]').each(function(){
      $(this).prop('checked', status);
   });
}
</script>
</head>
<body>
<h1>Select and deselect all checkbox using jQuery</h1>
<input type="checkbox" id="selectall" onclick='selectAll(this.checked)'/>Select all<br />
<input type="checkbox" class="selectedId" name="selectedId" id="1" />1 <br />
<input type="checkbox" class="selectedId" name="selectedId" id="2" />2 <br />
<input type="checkbox" class="selectedId" name="selectedId" id="3" />3 <br />
</body>
</html>



No comments:

Post a Comment