Table header checkbox checked all in html by using JQuery

Select All Checkboxes When Table Header Checkbox is Checked

In this article, we will discuss how to implement a feature that allows users to select all checkboxes in a table when a header checkbox is checked. This functionality is often desired in web applications and can be implemented using a combination of HTML, CSS, and jQuery.

HTML Markup Code

Let's start by examining the HTML markup used to create the table with checkboxes.


<div style='width:100%; text-align:center;'>
<table>
<tr>
  <th colspan='1'>
    <input id='chk' type='checkbox' value='header'/>
  </th>
  <th colspan='2'>Header CheckBox
</tr>
<tr>
  <td><input type='checkbox' value='1' /></td>
  <td>John</td>
  <td>Sena</td>  
</tr>
<tr>
  <td><input type='checkbox' value='2' /></td>
  <td>Under</td>
  <td>Taker</td>  
</tr>
<tr>
  <td><input type='checkbox' value='3'/></td>
  <td>Big</td>
  <td>Show</td>  
</tr>
<tr>
  <td><input type='checkbox' value='4'/></td>
  <td>The Great</td>
  <td>Kali</td>  
</tr>
</table>
</div>

CSS StyleSheet Code

Apply some basic styling to the table using CSS.


<style>

    table {
        border-collapse: collapse;
        width: 100%;
    }

    table th {
        border: 1px solid #999;
        background-color: #999;
        color: #fff;
        text-align: center;
        padding-left: 10px;
    }

    table td {
        padding: 3px;
    }
</style>

JQuery Code

Now, let's add jQuery code to handle the checkbox interactions.


<script>

$("#chk").change(function () {
        if ($(this).is(':checked')) {
            $("input[type=checkbox]").each(function (index) {
                if ($(this).prop('checked', true)) {
                    var value = $(this).val();
                }
            });
        } else {
            $("input[type=checkbox]").each(function (index) {
                if ($(this).prop('checked', false)) {
                    var value = $(this).val();
                }
            });
        }
    });

    $("input[type=checkbox]").change(function () {
        var allChecked = true;
        $("input[type=checkbox]").each(function (index) {
            if (!$(this).is(':checked')) {
                allChecked = false;
            }
        });
        $("#chk").prop('checked', allChecked);
    });


</script>

This jQuery code ensures that when the header checkbox is checked or unchecked, all checkboxes in the table follow suit. Additionally, it updates the header checkbox based on the individual checkboxes' state.

Feel free to use and adapt this code to enhance the user experience in your web applications where selecting multiple checkboxes is required.

Post a Comment

0 Comments