Click here to Skip to main content
15,885,757 members
Articles / Web Development / ASP.NET

Validating checkboxes or other controls inside a DataGrid using JavaScript

Rate me:
Please Sign up or sign in to vote.
1.63/5 (6 votes)
16 May 2007CPOL 19.6K   11  
Validating DataGrid at the client side using JavaScript.

Introduction

Situations arise often to validate checkbboxes, textboxes, or dropdownboxes inside a DataGrid on the client-side. In this article, we will see how we can do this.

Background

Here I am providing an example where the requirement is to find out whether at least one checkbox is checked before submission of the page. There are three DataGrids on the page and the number of checkboxes inside each is dynamically determined.

Using the Code

The JavaScript function that fetches the checked status of the checkboxes inside a DataGrid is given below:

JavaScript
function getCheckedDetails(index,result, datagridname)
{
    var id = datagridname + "__ctl" + index + "_chkSelect1" ;            
                 
    if(document.getElementById(id))
    {
        if(document.getElementById(id).checked == true)
        {
            result = "F" ;
        }    
                
        if(result == "F")
        {
            return result ;
        }
        else
        {
            index = index + 1 ;
            result = getCheckedDetails(index, 'T',datagridname);
        }
    }
    return result ;        
}

This JavaScript function is invoked by the ValidateSubmit() function:

JavaScript
function ValidateSubmit()
{
    var resultL1 = getCheckedDetails(2,'T','L1') ;
    var resultL2 = getCheckedDetails(2,'T','L2') ;
    var resultL3 = getCheckedDetails(2,'T','L3') ;
    if(resultL1 == "T" && resultL2 == "T" && resultL3 == "T")
    {
        alert("Select atleast one checkbox");
        return false;
    }

}

This function is added to the attributes of the Submit button in the code-behind.

JavaScript
btnSubmit.Attributes.Add("onclick","return ValidateSubmit()")

Points of Interest

The same approach can be used to validate any type of control inside a DataGrid at client side.

License

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


Written By
Web Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --