How To Select All CheckBoxes using JQuery

This example demonstrates how to select all the checkboxes using JQuery. It is one of the common requirement in many of the applications, when there is multiple checkboxes in a page, we have to keep an option for “select all” and when all the checkboxes got selected, by default “select all” check box also to be selected. Here I have written a simple example to demonstrate that.

<!DOCTYPE html>
<html>
<head>
    <title>How to Check All Check Boxes using JQuery</title>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script type="text/javascript">
         $(function () {

            var chkId = '';
            $('.chkNumber:checked').each(function () {
                chkId += $(this).val() + ",";
            });
            chkId = chkId.slice(0, -1);

           $('.chkSelectAll').change(function () {
                $('.chkNumber').prop('checked', this.checked);
            });

     $('.chkNumber').change(function() { $('.chkSelectAll').prop('checked',$('.chkNumber:checked').length == $('.chkNumber').length);
     });

        });
    </script>
</head>
<body>
    <h2>Select All Check Boxes using JQuery</h2>
    <table id="mytable">
        <tr>
            <td>
                <input type="checkbox" class="chkSelectAll" />SelectAll
            </td>
            <td><input type="checkbox" class="chkNumber" value="1" />One</td>
            <td><input type="checkbox" class="chkNumber" value="2" />Two</td>
            <td><input type="checkbox" class="chkNumber" value="3" />Three</td>
            <td><input type="checkbox" class="chkNumber" value="4" />Four</td>
            <td><input type="checkbox" class="chkNumber" value="5" />Five<br /></td>
        </tr>
    </table>
</body>
</html>

JQuery CheckBox Demo

checkbox-all

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*