Tuesday, April 15, 2014

Select/Deselect all using check box in jQuery

In this article am going to explain how to select/deselect multiple checkbox using jQuery.

HTML Code

<div class="wrapContainer">
  <div class="codeContainer">
    <p class="Blue">
    <table border="1">
  <tr>
    <th><input type="checkbox" id="selectall"/></th>
    <th>Cell phone</th>
    <th>Rating</th>
  </tr>
  <tr>
    <td align="center"><input type="checkbox" class="case" name="case" value="1"/></td>
    <td>BlackBerry Bold 9650</td>
    <td>2/5</td>
  </tr>
  <tr>
    <td align="center"><input type="checkbox" class="case" name="case" value="2"/></td>
    <td>Samsung Galaxy</td>
    <td>3.5/5</td>
  </tr>
  <tr>
    <td align="center"><input type="checkbox" class="case" name="case" value="3"/></td>
    <td>Droid X</td>
    <td>4.5/5</td>
  </tr>
  <tr>
    <td align="center"><input type="checkbox" class="case" name="case" value="4"/></td>
    <td>HTC Desire</td>
    <td>3/5</td>
  </tr>
  <tr>
    <td align="center"><input type="checkbox" class="case" name="case" value="5"/></td>
    <td>Apple iPhone 4</td>
    <td>5/5</td>
  </tr>
</table>
  </div>
</div>



Jquery Code

Need to include jQuery library function.Copy and paste the following jQuery code. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <SCRIPT language="javascript">
$(function(){

    // add multiple select / deselect functionality
    $("#selectall").click(function () {
          $('.case').attr('checked', this.checked);
    });

    // if all checkbox are selected, check the selectall checkbox
    // and viceversa
    $(".case").click(function(){

        if($(".case").length == $(".case:checked").length) {
            $("#selectall").attr("checked", "checked");
        } else {
            $("#selectall").removeAttr("checked");
        }

    });
});
</SCRIPT>

Demo

Cell phone Rating
BlackBerry Bold 9650 2/5
Samsung Galaxy 3.5/5
Droid X 4.5/5
HTC Desire 3/5
Apple iPhone 4 5/5

3 comments:

  1. if i want to get the data of all the selected(checked) rows into another table, could plz post that code

    ReplyDelete
  2. @Balraj, just include name="getData[]", then submit the data of checkboxes using ajax and $('#formname').serialize();

    ReplyDelete
  3. @Balraj, just include name="getData[]", then submit the data of checkboxes using ajax and $('#formname').serialize();

    ReplyDelete