Thursday, November 12, 2009

CheckBoxList Required Validation in Javascript

ASP.NET CODE:

<asp:CheckBoxList ID="chkList" runat="server">
<asp:ListItem>Item One</asp:ListItem>
<asp:ListItem>Item two</asp:ListItem>
<asp:ListItem>Item three</asp:ListItem>
<asp:ListItem>Item four</asp:ListItem>
</asp:CheckBoxList>
<asp:Button ID="btnSubmit" runat="server" ValidationGroup="CHK" OnClientClick="return validateChk();" Text="Validate"/>

JAVASCRIPT CODE:


function validateChk() {
debugger;
var found = false;
var validated = false;
var id = document.getElementById("<%=chkList.ClientID %>").id;
var elements = document.forms[0].elements;
for (i = 0; i < elements.length; i++) {
if (elements[i].type == "checkbox" && elements[i].id.indexOf(id) > -1) {
found = true;
if (elements[i].checked) {
validated = true;
break;
}
}
}
if (found && validated)
return true;
else
return false;

}

No comments:

Post a Comment

Please add your valuable comments about this post if it helped you. Thanks