Gridview checkbox validation using javascript
Labels: Gridview, Javascript
Introduction:
Hi here I will explain how to check the checked status of checkboxes in gridview using JavaScript
Description:
I have a one gridview with checkboxes and one button if user clicks on button I need to raise validation if user doesn’t checked at least one checkbox in gridview for that I have written one JavaScript function to check whether checkboxes selected in gridview or not.
For that write the following code in aspx page
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Check all checkboxes if Header checkbox checks</title>
<style type="text/css">
.Gridview
{
font-family:Verdana;
font-size:10pt;
font-weight:normal;
color:black;
width:500px;
}
</style>
<script type="text/javascript" language="javascript">
function validateCheckBoxes() {
var isValid = false;
var gridView = document.getElementById('<%= gvcheckbox.ClientID %>');
for (var i = 1; i < gridView.rows.length; i++) {
var inputs = gridView.rows[i].getElementsByTagName('input');
if (inputs != null) {
if (inputs[0].type == "checkbox") {
if (inputs[0].checked) {
isValid = true;
return true;
}
}
}
}
alert("Please select atleast one checkbox");
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:gridview id="gvcheckbox" cssclass="Gridview" runat="server" autogeneratecolumns="False" xmlns:asp="#unknown">
HeaderStyle-BackColor="#7779AF" HeaderStyle-ForeColor="white">
<columns><asp:templatefield>
<HeaderTemplate>
<asp:checkbox id="chkheader" runat="server" />
</HeaderTemplate>
<itemtemplate>
<asp:checkbox id="chkchild" runat="server" />
<HeaderStyle HorizontalAlign="Left" />
<itemstyle horizontalalign="Left">
<asp:boundfield headertext="UserName" datafield="UserName" headerstyle-horizontalalign="Left" />
<asp:boundfield headertext="FirstName" datafield="FirstName" headerstyle-horizontalalign="Left" />
<asp:boundfield headertext="LastName" datafield="LastName" headerstyle-horizontalalign="Left" />
<asp:button runat="server" text="Submit" onclientclick="javascript:validateCheckBoxes()" xmlns:asp="#unknown" />
</form>
</body>
</html>
In code behind bind gridview with some data and check it will work for you
DEMO!