How to handle checkbox using jQuery

Monday, August 29, 2011

Checkbox is one of most used form element in web. It is used to define the state like on or off. We generally need to modify its state in response to client event. For this jQuery is very handy to manipulate the state of checkbox. jQuery is a javascript framework for simplifying javascript coding. There are several ways to find out if the checkbox is checked or not using jQuery
$('input[name=foo]').is(':checked')
$('input[name=foo]').attr('checked')
The state of the checkbox can be changed by changing the attribute 'checked' by using 'attr' method of jQuery.
For checked state:
$('input[name=foo]').attr('checked', true);

To uncheck the checkbox:
$('input[name=foo]').attr('checked', false);
Demo
Let us take an example HTML form.

<p><a href="#" id="btn_all">ALL</a>&nbsp;<a href="#" id="btn_none">NONE</a>&nbsp;<a href="#" id="btn_reverse">REVERSE</a></p>
<form action="" method="post" name="form1" id="form1">
  <table width="100%" border="0" cellspacing="0" cellpadding="0">
    <tr>
      <td width="25"><input name="ch1" id="ch1" type="checkbox" value="A" /></td>
      <td>First</td>
    </tr>
    <tr>
      <td><input name="ch2" id="ch2" type="checkbox" value="B" /></td>
      <td>Second</td>
    </tr>
    <tr>
      <td><input name="ch3" id="ch3" type="checkbox" value="C" /></td>
      <td>Third</td>
    </tr>
    <tr>
      <td><input name="ch4"  id="ch4" type="checkbox" value="D" /></td>
      <td>Fourth</td>
    </tr>
    <tr>
      <td><input name="ch5" id="ch5" type="checkbox" value="E" /></td>
      <td>Fifth</td>
    </tr>
  </table>
</form>

We have three links which we will treat as buttons for selecting all, deselecting all and reversing the status. Below is the javascript code for the purpose.

jQuery(document).ready(function($){
 //
 $('#btn_all').click(function(e){
  e.preventDefault();
  $("#form1 input:checkbox").attr("checked",true)
 });
 //
 $('#btn_none').click(function(e){
  e.preventDefault();
  $("#form1 input:checkbox").attr("checked",false)
 });
 //

 $('#btn_reverse').click(function(e){
  e.preventDefault();
  $("#form1 input:checkbox").each(function(){
   this.checked=!this.checked;
  });
 });

});

Demo

0 comments:

Post a Comment

 
back to top