Ad

Friday, 13 June 2014

How to implement SelectAll Checkbox using Jquery

Some times we may need to implement the Selectall checkbox in our pages.On Checking the Select all check box,it will check all the check boxes under it and unchecking it,will deselect all the Check boxes.Jquery sample for Select All functionality is shown below

<html>
  <head>
    <title>Selecall Checkbox sample</title>
<script type="text/javascript" src="jquery-2.1.1.min.js" ></script>
<script type="text/javascript">
    $(document).ready(function() {
     
     /*Handler For SelectAll Checkbox*/ 
      $("#selectallchkbox").change(function(){
        $('.tvChkBox').prop("checked",$(this).prop("checked"));
       });

      /*Handler For rest of the checkbox*/      
       $('.tvChkBox').change(function(){
       if( $('.tvChkBox').length==$('.tvChkBox:checked').length)
         {
           $("#selectallchkbox").prop("checked",true);    
         }
         else
         {
           $("#selectallchkbox").prop("checked",false);
         }         
       });

    });
</script>
</head>
<body>
<table bgcolor="#E9E9E9" border="1">
<tr>
<td>
<B>Selectall Sample</B><BR><BR>
<table border='1'>
<tr>
<th><input type="checkbox" id="selectallchkbox"/></th>
<th>TV Brand</th>
<th>Rank</th>
</tr>
<tr><td><input class="tvChkBox" type="checkbox" id="tvChkBox1"/></td><td>Sony</td><td>1</td></tr>
<tr><td><input class="tvChkBox" type="checkbox" id="tvChkBox2"/></td><td>Samsung</td><td>3</td></tr>
<tr><td><input class="tvChkBox" type="checkbox" id="tvChkBox3"/></td><td>LG</td><td>2</td></tr>
<tr><td><input class="tvChkBox" type="checkbox" id="tvChkBox4"/></td><td>Onida</td><td>4</td></tr>
</table>
</td>
</tr>
</table>
</body>
</html>

  • When the page document is ready(i.e on load of the page),the Javascript code inside the $(document).ready will be get executed.
  • We registered two handlers in the ready section.
  • Change Handler for SelectAll CheckBox- On change of SelectAll check box,if it is checked we select all the Checkboxes with the class "tvChkBox" and  if it is unchecked we uncheck the same(by setting the property "checked" to true or false).
  • Change Handler for rest of the Checkboxes - On change of the Checkboxes with the class "tvChkBox",if all the Checkboxes with  the class "tvChkBox" is checked we will check the selectall Checkbox,otherwise will uncheck the selec all checkbox(by setting the property "checked" to true or false).  
 Demo:


Selectall Sample

TV Brand Rank
Sony1
Samsung3
LG2
Onida4

1 comment:

  1. http://justwebcode.blogspot.com/2017/07/select-all-checkboxes-in-a-row-following-checked-checkbox.html

    ReplyDelete