Check or Uncheck All Checkboxes in a Repeater Control using jQuery .prop() method

← PrevNext →

Web developers often use an Asp.Net Repeater control to display a list of data, by binding the control to various data source such as a database or an XML. You can also add checkbox and other controls to a repeater to add some dynamic features to it. Here, I’ll show you how to check or uncheck all checkboxes in a repeater control using jQuery.

This is essential to ensure that your user quickly select or unselect all the checkboxes if the repeater has many rows of data attached to it.

Therefore, let’s first add a repeater control to our web page and bind it to a database table using code behind procedure.

Related: Extract Files from Folder and Show it in a Repeater Control

The Markup

Open the toolbox in the design mode and add a repeater control. Get back to the source window; you will see the repeater with opening and closing tags.

You will now have to add three templates to the repeater for header, items and footer.

<!DOCTYPE html>
<html>
<head>
    <title>Checkboxes in Repeater Control</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

    <style>
        table, th, td {
            font:13px Verdana;
            border:solid 1px #CCC;
            padding:2px 3px;
        }
        th {
            background:#CCC;
            color:#FFF;
            text-align:center;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <div>
            <asp:Repeater ID="Repeater1" runat="server">
                <HeaderTemplate>
                    <<%--ADD HEADER TO THE REPEATER.--%>
                    <table>
                        <tr>
                            <th><asp:CheckBox ID="chkAll" runat="server" /></th>
                            <th>ID</th>
                            <th>Employee Name</th>
                            <th>Designation</th>
                            <th>Department</th>
                            <th>DOJ</th>
                        </tr>
                </HeaderTemplate>

                <ItemTemplate>
                    <%--ADD ITEMS TO EACH TABLE ROW.--%>
                    <tr>
                        <td><asp:CheckBox ID="chkRowData" runat="server" /></td>
                        <td><%#Eval("EmpID")%></td>
                        <td><%#Eval("EmpName")%></td>
                        <td><%#Eval("Designation")%></td>
                        <td><%#Eval("Department")%></td>
                        <td><%#Eval("JoiningDate", "{0:dd/MM/yyyy}")%></td>
                    </tr>
                </ItemTemplate>

                <FooterTemplate>
                    </table>            <%--CLOSE table TAG IN FOOTER.--%>
                </FooterTemplate>
            </asp:Repeater>
        </div>
    </div>
    </form>
</body>

Now, I’ll bind the above repeater with a database table when the web page loads. Therefore, I’ll write the binding code in the form_load (or page_load) procedure.

Code behind (C#)
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;        // FOR "DataTable"

public partial class SiteMaster : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // SET THE CONNECTION STRING.
            string sCon = "Data Source=DNA;Persist Security Info=False;Integrated Security=SSPI;" + 
                "Initial Catalog=DNA_Classified;User Id=sa;Password=;Connect Timeout=30;";

            using (SqlConnection con = new SqlConnection(sCon))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT *FROM dbo.Employee"))
                {
                    SqlDataAdapter sda = new SqlDataAdapter();
                    try
                    {
                        cmd.Connection = con;
                        con.Open();
                        sda.SelectCommand = cmd;

                        DataTable dt = new DataTable();
                        sda.Fill(dt);

                        // BIND DATABASE WITH THE REPEATER.
                        Repeater1.DataSource = dt;
                        Repeater1.DataBind();
                    }
                    catch (Exception ex)
                    {
                        //
                    }
                }
            }
        }
    }
}
Code behind (Vb.Net)
Option Explicit On
Imports System.Data             ' FOR "DataTable"
Imports System.Data.SqlClient

Partial Class Site
    Inherits System.Web.UI.MasterPage

    Protected Sub form1_Load(sender As Object, e As System.EventArgs) Handles form1.Load
        If Not IsPostBack Then

            ' SET THE CONNECTION STRING.
            Dim sCon As String =
                "Data Source=DNA;Persist Security Info=False;Integrated Security=SSPI;" & _
                 "Initial Catalog=DNA_Classified;User Id=sa;Password=;Connect Timeout=30;"

            Using con As SqlConnection = New SqlConnection(sCon)
                Using cmd As SqlCommand = New SqlCommand("SELECT *FROM dbo.Employee")

                    Dim sda As SqlDataAdapter = New SqlDataAdapter
                    Try
                        cmd.Connection = con : con.Open()
                        sda.SelectCommand = cmd

                        Dim dt As DataTable = New DataTable
                        sda.Fill(dt)

                        ' BIND DATABASE WITH THE REPEATER.
                        Repeater1.DataSource = dt
                        Repeater1.DataBind()
                    Catch ex As Exception
                        '
                    End Try
                End Using
            End Using
        End If
    End Sub
End Class

When you run the program, the repeater will show all the data along with a checkbox each row and one checkbox on the header (the first column).

Related: Show Images with Description using a Repeater Control in Asp.Net – LINQ to XML - C#

Finally, let’s add the jQuery script to check or uncheck all the checkboxes in the row when a user clicks the header checkbox.

The jQuery Script
<script>
    $(document).ready(function () {
        // CHECK-UNCHECK ALL CHECKBOXES IN THE REPEATER 
            // WHEN USER CLICKS THE HEADER CHECKBOX.
        $('table [id*=chkAll]').click(function () {
            if ($(this).is(':checked'))
                $('table [id*=chkRowData]').prop('checked', true)
            else
                $('table [id*=chkRowData]').prop('checked', false)
        });

        // NOW CHECK THE HEADER CHECKBOX, IF ALL THE ROW CHECKBOXES ARE CHECKED.
        $('table [id*=chkRowData]').click(function () {

            var total_rows = $('table [id*=chkRowData]').length;
            var checked_Rows = $('table [id*=chkRowData]:checked').length;

            if (checked_Rows == total_rows)
                $('table [id*=chkAll]').prop('checked', true);
            else
                $('table [id*=chkAll]').prop('checked', false);
        });
    });
</script>
</html>

Two different events will execute the check all or uncheck all procedure in the repeater. The first event occurs when a user click the checkbox in header part. See how I have used the checkbox’s id in the click function. The second event checks or un-checks the header check, if (condition) when all the checkboxes in the repeater row are checked.

The jQuery .prop() (or property) method sets or returns properties and values of elements. Using this method I can alter the checkbox checked property. The value I’ll set is either true or false. The checked property is a Boolean.

Syntax

$(selector).prop(property,value)


Image showing how to set property “checked” in an Asp.Net Checkbox control

Check or Uncheck Checkboxes in a Repeater Control using jQuery

That’s it. If you have any queries or suggestions regarding this article and its example, then please leave a message below.

Thanks for reading .

← PreviousNext →