65.9K
CodeProject is changing. Read more.
Home

Validating checkboxes or other controls inside a DataGrid using JavaScript

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.63/5 (6 votes)

Apr 6, 2007

CPOL
viewsIcon

19774

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:

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:

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.

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.