Click here to Skip to main content
15,122,728 members
Articles / Web Development / HTML
Article
Posted 22 Jan 2008

Stats

210.1K views
1.2K downloads
70 bookmarked

Client-Side Validation for the CheckBoxes Inside a GridView

Rate me:
Please Sign up or sign in to vote.
3.72/5 (38 votes)
9 May 2008CPOL1 min read
This article describes how to count the selected checkboxes inside a GridView control.

demo.gif

Introduction

I am presenting here a JavaScript code that ensures that at least one checkbox is checked among the checkboxes in a particular column inside a GridView control before submitting a form.

Using the code

I have used a TemplateField inside the GridView and put a CheckBox in the ItemTemplate of the TemplateField.

The HTML code looks like this:

ASP.NET
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
   <Columns> 
      <asp:BoundField HeaderText="n" DataField="sno"> 
       <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />
          <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
      </asp:BoundField>                
       <asp:TemplateField HeaderText="Select">
            <ItemTemplate>
               <asp:CheckBox ID="chkBxSelect" runat="server" />
            </ItemTemplate>
            <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" />
            <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
        </asp:TemplateField>
     </Columns>
  </asp:GridView>
 <asp:Button ID="btnPost" runat="server" Text="Post" 
             OnClientClick="javascript:return TestCheckBox();"
             OnClick="btnPost_Click" />

Attach a OnClientClick event to the button [btnPost]:

ASP.NET
<asp:Button ID="btnPost" runat="server" Text="Post" 
            OnClientClick="javascript:return TestCheckBox();"
            OnClick="btnPost_Click" />

Add this JavaScript in the page’s head section:

JavaScript
<script type="text/javascript">
   var TargetBaseControl = null;
        
   window.onload = function()
   {
      try
      {
         //get target base control.
         TargetBaseControl = 
           document.getElementById('<%= this.GridView1.ClientID %>');
      }
      catch(err)
      {
         TargetBaseControl = null;
      }
   }
        
   function TestCheckBox()
   {              
      if(TargetBaseControl == null) return false;
      
      //get target child control.
      var TargetChildControl = "chkBxSelect";
            
      //get all the control of the type INPUT in the base control.
      var Inputs = TargetBaseControl.getElementsByTagName("input"); 
            
      for(var n = 0; n < Inputs.length; ++n)
         if(Inputs[n].type == 'checkbox' && 
            Inputs[n].id.indexOf(TargetChildControl,0) >= 0 && 
            Inputs[n].checked)
          return true;        
            
      alert('Select at least one checkbox!');
      return false;
   }
</script>

In the above script, the global variable TargetBaseControl has been initialized in the window.onload event in order to get the reference of the parent control [GridView]. The function TestCheckBox first gets the array of all ‘input’elements inside the parent control. After that, it iterates all the elements of the array and tests a condition, and if the condition is found to be true, it returns true indicating that at least one checkbox is checked inside the GridView; else it displays a message and returns false. The condition tests the elements of a specific type in a particular column inside the parent element.

Just download the sample application and enjoy coding! I hope you will like this article.

Features of this script

This script is cross-browser compatible and fast as it iterates elements of a specific tag inside a target element [GridView] rather than iterating in a whole form. It searches the elements of a specific type in a particular column of the target element [GridView].

Supporting browsers

I have tested this script on the following browsers:

Browsers.png

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Samir NIGAM
Technical Lead Infogain India Pvt Ltd
India India


Samir NIGAM is a Microsoft Certified Professional. He is an insightful IT professional with results-driven comprehensive technical skill having rich, hands-on work experience n web-based applications using ASP.NET, C#, AJAX, Web Service, WCF, jQuery, Microsoft Enterprise Library , LINQ, MS Entity Framework, nHibernate, MS SQL Server & SSRS.



He has earned his master degree (MCA) from U.P. Technical University, Lucknow, INDIA, his post graduate dipoma (PGDCA ) from Institute of Engineering and Rural Technology, Allahabad, INDIA and his bachelor degree (BSc - Mathematics) from University of Allahabad, Allahabad, INDIA.



He has good knowledge of Object Oriented Programming, n-Tier Architecture, SOLID Principle, and Algorithm Analysis & Design as well as good command over cross-browser client side programming using JavaScript & jQuery,.



Awards:



Comments and Discussions

 
GeneralRe: Very good Pin
Samir NIGAM29-Jan-08 3:08
MemberSamir NIGAM29-Jan-08 3:08 
GeneralNice concept Pin
joohitha29-Jan-08 2:18
Memberjoohitha29-Jan-08 2:18 
GeneralRe: Nice concept Pin
Samir NIGAM29-Jan-08 3:06
MemberSamir NIGAM29-Jan-08 3:06 
GeneralVery Nice Concept Pin
Sandeep Shekhar27-Jan-08 20:02
MemberSandeep Shekhar27-Jan-08 20:02 
GeneralRe: Very Nice Concept Pin
Samir NIGAM27-Jan-08 21:42
MemberSamir NIGAM27-Jan-08 21:42 
Generalgood work Pin
Abhijit Jana24-Jan-08 22:27
professionalAbhijit Jana24-Jan-08 22:27 
GeneralRe: good work Pin
Samir NIGAM24-Jan-08 23:04
MemberSamir NIGAM24-Jan-08 23:04 
GeneralGood Work Pin
Ajay Singh23-Jan-08 18:53
MemberAjay Singh23-Jan-08 18:53 
Sameer good work keep going on..

One more thing that this code Asp.net 2.0 and in which there is property "OnClientClick". so you can replace the below

btnPost.Attributes["onclick"] = "javascript:return TestCheckBox();";

by just setting the "OnClientClick" property value with "return TestCheckBox()".

rest is I think fine.

Ajay
GeneralRe: Good Work Pin
Samir NIGAM23-Jan-08 19:06
MemberSamir NIGAM23-Jan-08 19:06 
GeneralRe: Good Work Pin
Samir NIGAM24-Jan-08 2:35
MemberSamir NIGAM24-Jan-08 2:35 
GeneralSuccess Story Pin
knptech23-Jan-08 18:50
Memberknptech23-Jan-08 18:50 
GeneralRe: Success Story Pin
Samir NIGAM21-May-08 19:03
MemberSamir NIGAM21-May-08 19:03 
GeneralGood Script Pin
248912823-Jan-08 18:07
Member248912823-Jan-08 18:07 
GeneralRe: Good Script Pin
Samir NIGAM21-May-08 19:03
MemberSamir NIGAM21-May-08 19:03 
GeneralGreat Work Pin
I Never Look Behind23-Jan-08 17:57
MemberI Never Look Behind23-Jan-08 17:57 
GeneralRe: Great Work Pin
Samir NIGAM21-May-08 19:04
MemberSamir NIGAM21-May-08 19:04 
GeneralBUG: Pin
Kevin Jensen23-Jan-08 8:53
MemberKevin Jensen23-Jan-08 8:53 
GeneralRe: BUG: Pin
Samir NIGAM23-Jan-08 17:44
MemberSamir NIGAM23-Jan-08 17:44 
GeneralRe: BUG: Pin
Samir NIGAM24-Jan-08 2:35
MemberSamir NIGAM24-Jan-08 2:35 
GeneralExactly what i've been looking for. GREAT STUFF!! Pin
Kevin Jensen23-Jan-08 7:26
MemberKevin Jensen23-Jan-08 7:26 
GeneralRe: Exactly what i've been looking for. GREAT STUFF!! Pin
Samir NIGAM21-May-08 19:04
MemberSamir NIGAM21-May-08 19:04 
GeneralGood job Pin
MCSDvikasmisra22-Jan-08 22:16
MemberMCSDvikasmisra22-Jan-08 22:16 
GeneralRe: Good job Pin
Samir NIGAM22-Jan-08 22:39
MemberSamir NIGAM22-Jan-08 22:39 
GeneralRe: Good job Pin
Samir NIGAM24-Jan-08 2:35
MemberSamir NIGAM24-Jan-08 2:35 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.