Tuesday, April 30, 2013

Select multiple checkboxes using Javascript and jQuery

Suppose, we have a form as shown below.



It has 3 buttons, when the "Select All" button is clicked, all the checkboxes are checked, while "Select None" button unchecks all the chekboxes. Now, we need to write two javascirpt functions which checks/unchecks all the checkboxes at once. Check out the code below.

<html>
<head>
<script type='text/javascript'>

function fselect_all()
{
 // IE 8 and others support querySelectorAll()
 var col = document.querySelectorAll("input[type=checkbox]");
 for(var i=0; i<col.length; i++ )
 {
   col[i].checked = true; // Check
 }
}

function fselect_none()
{
  // IE 8 and others support querySelectorAll()
 var col = document.querySelectorAll("input[type=checkbox]");
 for(var i=0; i<col.length; i++ )
 {
   col[i].checked = false; // Uncheck
 }
}
</script>
</head>
<body>

<form>
<table>
 <!-- Dynamic Generation of Table Items -->
<?php
  for( $i=1;$i<=10; $i++)
  {
?>
   <tr>
    <td>
      <input type='checkbox' name="sel[<?php echo $i;?>]">
      Item <?php echo $i;?> </td>
   </tr>
<?php 
  }
?> 
 <tr>
  <td>
    <input type='button' value='Select All' onclick='fselect_all()'>
    <input type='button' value='Select None' onclick='fselect_none()'>
    <input type='submit' value='Submit' name='btn_submit'>
  </td>
 </tr>
</table>
</form>
</body>
</html>


Some points to be noticed in the above piece of code ::
1. We are generating the checkboxes using a PHP for loop which generates the following table rows ..

 <tr><td><input type='checkbox' name="sel[1]">  Item 1 </td></tr>
 <tr><td><input type='checkbox' name="sel[2]">  Item 2 </td></tr>

  ...
2. In the fselect_all()  and fselect_none() functions, we are using querySelectoAll() method which is supported in all new browsers. IE8 onwards have support for it. This function takes CSS like selectors for selecting DOM nodes and returns all the matching node/elements as a collection it finds. Then we simply run a Javascript for() loop to iterate each checkbox item and then we set their "checked" property to true or false as needed.

The above task can be easily done using jQuery. Check the new fselect_all() and fselect_none() functions which use jQuery statements for checking/unchecking checkboxes.

function fselect_all()
{
  $("input[type=checkbox]").each(function(){ this.checked = true; });
}

function fselect_none()
{
  $("input[type=checkbox]").each(function(){ $(this).removeAttr('checked'); });
}


The statement " this.checked = true; " is a Javascript one, using the statement $(this).attr('checked',true); instead checks the checkboxes only once. This phenomenon can be seen on jsFiddle. Hence we better use the old Javascript statement for checking all checkboxes.

To add checked='checked' to a Checkbox, we can use jQuery's prop() method. And to remove the check, instead of using removeAttr('checked') we can use removeProp(' checked') method. Adding  checked='checked' using the prop() method may not appear in FireBug etc tools.

Now, we would submit the form and see how the inputs are captured at the server end. Check the PHP code below.

<?php
if( isset($_REQUEST['sel']) )
{
   /// Iterate the Items
   foreach( $_REQUEST['sel'] as $key => $val)
   {
     /// Get the ID
     $customer_id = $key;
    
     /// Do some SQL queries
     ...
   }

}

?>

Only selected items will be captured in the above array at the server side. In the PHP loop above, $val for all the array items would have a value of "on". When a checkbox is checked and submitted, server gets a value of "on" against the element's name unless a value is specified as shown below :

<input type='checkbox' name='sel[]' value='test 1'>

1 comment:

shashank mishra said...

thank u for your post