Validate at least one Checkbox is checked in GridView using JQuery

No.of Views11495
Bookmarked1 times
Downloads 
Votes0
By  RRaveen   On  30 Dec 2010 09:12:20
Tag : JQuery , Grid Controls
In this article I will demonstration to how to validate whether to check at least one checkbox is checked in the Gridview in ASP.NET using JQuery. The JQuery is significant library to manipulate client html and css with less line of code.Before Jquery come up we have used the pure JavaScript to implement this features. I will give the JavaScript code as well in end of this article.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

In this article I will demonstration to how to validate whether to check at least one checkbox is checked in the Gridview in ASP.NET using JQuery. The JQuery is significant library to manipulate client html and css with less line of code.Before Jquery come up we have used the pure JavaScript to implement this features. I will give the JavaScript code as well in end of this article.

Implementation

Step 1
    As usual create a new web project using visual studio 2008 and give name to project is “CheckAtleastOne”.
Note: you can use any name to project.

Step 2
    Add a GridView with few columns as like below,
Html Code

<asp:GridView ID="gvpub" runat="server" AutoGenerateColumns="False">
                <Columns>
                    <asp:TemplateField>
                        <HeaderTemplate>
                          Selection
                        </HeaderTemplate>
                        <ItemTemplate>
                            <asp:CheckBox runat="server" ID="chkSelection" />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:BoundField DataField="Name" HeaderText="Name" />
                    <asp:BoundField DataField="Address1" HeaderText="Address1" />
                    <asp:BoundField DataField="Address2" HeaderText="Country" />
                    <asp:BoundField DataField="Company" HeaderText="Company" />
                </Columns>
            </asp:GridView>

The first column has a template field to customize the header and row for this column. The header template header is call Selection. The item template will have checkbox for represent each row.
Finally add a submit button to perform the server side click event. When user click save button we will validate at least checkbox is checked or not if not check prompt message otherwise continue to server side task.

Step 3
    Let’s create a simple data source to bind to grid view. This data source is custom object collection of the publishers.

Note: I have attached sample project end of this article you can download it. And also you can use any data source to bind GridView.

C# Code

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class checkanduncheckdemo : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            List<Publisher> collectionOfPub = new List<Publisher>();
            collectionOfPub.Add(new Publisher("Wrox", "No-02,John Ave 2", "US", "WROX"));
            collectionOfPub.Add(new Publisher("Apress", "No-03,Cels Ave 6", "US", "APRESS"));
            collectionOfPub.Add(new Publisher("Sams", "No-89,Test Ave 32", "US", "SAMS"));
            collectionOfPub.Add(new Publisher("Orelly", "No-23/08,John Ave 23", "US", "ORELLY"));
            collectionOfPub.Add(new Publisher("Packtpub", "No-56,John Ave 5", "INDIA", "PACKTPUB"));
            this.gvpub.DataSource = collectionOfPub;
            this.gvpub.DataBind();
        }


    }
}

Run project and see the output as like below,

Output 

Image Loading

Step 4
    In order work with JQuery, we have to add JQuery library in page as like below,
JavaScript

<script language="javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">
</script>

Step 5
    Now write few lines of JavaScript code to access checkbox controls within GridView with button click to implement features of this article aspiration.

JavaScript

<script language="javascript">
     $(document).ready(function(){    
        $('#btnsave').click(function(){   
           var chkboxrowcount = $("#<%=gvpub.ClientID%> input[id*='chkSelection']:checkbox:checked").size();   
           if (chkboxrowcount==0)
           {
                alert("please select at least a record");
                return false;         
           }
           return true;
       });
    });

    </script>

Code Explanation

1.    As usual first line is declare document ready event
2.    In the next line is register click event for save button in order validate checkbox when user click save button

$('#btnsave').click(function(){  //code });

3.    Next line is important to get no of check box is checked within GridView.

var chkboxrowcount = $("#<%=gvpub.ClientID%> input[id*='chkSelection']:checkbox:checked").size(); 

Two key points there in above line

  •   "#<%=gvpub.ClientID%> input[id*='chkSelection']:checkbox its return all type input control is checkbox with ID contains chkSelection.
  • …:checked").size(); is get number of checkbox is only checked.

4.    Then check is count is check is 0 then at least one checkbox is not checked and prompt message and return false to prevent server side task. Otherwise continue perform the server side task.

if (chkboxrowcount==0)
  {
   alert("please select at least a record");
   return false;         
    }
  return true;

Now let’s give old model(pure javascript code to implement same features.

Javascript

function IsSelectedAtleastOneCheckBox()
        
        {
          var loTable=document.all("<%=gvpub.ClientID%>"); // GridView Name
                    count=0;
                    with(document.forms[0])
                        {
                            for(var i=0;i<elements.length;i++)
                                {
                                    var e=elements[i];
                                    if(e.type == "checkbox" && e.checked==true && e.id.substring(e.id.lastIndexOf('_')+1,e.id.length) == 'ControlName') // This is our control Name
                                    {
                                        count += 1;
                                    }
                                }
                        }
                        if(count == 0)
                        {
                        alert("please select at least one ");
                        return false;
                        }
                        return true;
                
        }

Then you have to call in this function for button as like below

<asp:Button ID="btnsave" OnClientClick="return IsSelectedAtleastOneCheckBox();" runat="server"/>

So JQuery is best and less work to implement this kind of features than using pure JavaScript code.

Now run application and try it.

 

Image Loading

Live Demo

Check at least one  checkbox

Download Sample Project

Download source files -2 kb

Conclusion

In this article you have learned how to validate to check whether at least checkbox is checked in GridView in asp.net using JQuery before process to server side task, I have given live demonstration, so you try it now here. Thank you for reading, hopes help, please posts your all comments.

 
Sign Up to vote for this article
 
About Author
 
RRaveen
Occupation-Software Engineer
Company-TGS
Member Type-Gold
Location-Singapore
Joined date-03 Jun 2009
Home Page-codegain.com
Blog Page-www.codegain.com
- B.Sc. degree in Computer Science. - 4+ years experience in Visual C#.net and VB.net - Obsessed in OOP style design and programming. - Designing and developing Network security tools. - Designing and developing a client/server application for sharing files among users in a way other than FTP protocol. - Designing and implementing GSM gateway applications and bulk messaging. - Windows Mobile and Symbian Programming - Having knowledge with ERP solutions
 
 
Other popularSectionarticles
    The JQuery is powerful client side JavaScript library. Today I’m going to show you how to create cascading DropDownList using JQuery with JSON in ASP.NET.I hope you are all heard about cascading DropDownList and how to use with AJAX tool kit
    Published Date : 07/Dec/2010
    Today I have implemented to my project to check and uncheck all checkboxes within gridview in asp.net. So in this article we focus how to implement this features using JQuery with less code. And also I have given live demonstration as well you can try it in live.
    Published Date : 29/Dec/2010
    In this article, I will explain how to sort custom objects array using JQuery. Let’s say you have array with custom objects, the custom object has few attributes as well, so in this case, you may need to sort objects with different order with specific attributes.
    Published Date : 12/Jan/2011
    The JQuery is powerful library to manipulate client side HTML, CSS, object and etc. On this article I will explain how to sort element within array using JQuery. In this demonstration I will show sort for string and numeric elements.
    Published Date : 11/Jan/2011
    Today I have introduced the new features for CodeGain article submit page to count characters for description textbox with JQuery on time. The character counter is support to users to display how many characters have entered and how many chars remaining in live.
    Published Date : 25/Dec/2010
Comments
By:ganeshDate Of Posted:10/18/2013 5:20:17 AM
super
Superb
By:585Date Of Posted:7/17/2013 4:10:26 AM
8888
ddgdf
By:9Date Of Posted:9/7/2012 7:05:00 AM
9o
xc
By:Srinivasu DandamudiDate Of Posted:4/8/2011 12:15:08 AM
Gridview checkbox validation
Thanks RRaveen, it is working fine. Previously i used the below pure javascript, but it is working in IE only, but now i checked , it is working in all browsers. function ClientCheck() { var valid = false; var gv = document.getElementById("gv_Results"); for (var i = 0; i < gv.all.length; i ) { var node = gv.all[i]; if (node != null && node.type == "checkbox" && node.checked) { valid = true; break; } } if (!valid) { alert("Please select at least one checkbox."); } return valid; }
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top