65.9K
CodeProject is changing. Read more.
Home

How to validate atleast one checkbox is selected in a grid

starIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

1.00/5 (1 vote)

Jun 4, 2009

CPOL
viewsIcon

39942

How to validate atleast one checkbox is selected in a grid, from the client side.

Introduction

Here is the JavaScript code that ensures at least one checkbox is checked among the checkboxes inside a GridView control before submitting the form. A generalized function is provided which can be used for any grid. The base idea came from a fellow poster, Samir Nigam: http://www.codeproject.com/KB/webforms/GridViewcheckBoxes.aspx.

Using the code

In the DataGrid, I use a checkbox inside a template column, and attach an OnClientClick event to the button by passing the grid name and the checkbox name.

<asp:DataGrid ID="dgTry" runat="server">
    <Columns>
        <asp:BoundColumn DataField="name"></asp:BoundColumn>
        <asp:BoundColumn DataField="Age"></asp:BoundColumn>
        <asp:TemplateColumn>
         <ItemTemplate>
          <asp:CheckBox ID="chkSelect" runat="server"></asp:CheckBox>
         </ItemTemplate>
        </asp:TemplateColumn>
    </Columns>
</asp:DataGrid>

In the JavaScript section, I then add this piece of code:

<script language="javascript">
   function TestCheckBox(gridId,checkboxName)
   {    
      var TargetChildControl = checkboxName;
      var Inputs ;
            Inputs = gridId.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>

Now, add a button and add the OnClientClick event:

<asp:Button ID="btnSubmit" runat="server" 
  OnClick="Submit" OnClientClick="return TestCheckBox(dgTry,'chkSelect');" />

In the above code, we are passing the grid name and the checkbox name to the DataGrid. The function will find out all the input elements within the grid, and look if a checkbox with the name passed is checked. On the first instance it finds such a case, it returns true so a postback occurs, otherwise no.

Points of interest

While coding this, it was fun to find how the client ID could be passed to a function. Later, I figured out the ID of the control was sufficient.