Sunday, April 20, 2014

Validate ASP.Net CheckBoxList control using JavaScript (Select atleast one item)

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default11.aspx.cs" Inherits="Default11" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    
<script type = "text/javascript">
    var atLeast = 1
    function ValidateCheckBoxList() {
        var CHK = document.getElementById("<%=CheckBoxList1.ClientID%>");
        var checkbox = CHK.getElementsByTagName("input");
        var counter = 0;
        for (var i = 0; i < checkbox.length; i++) {
            if (checkbox[i].checked) {
                counter++;
            }
        }
        if (atLeast > counter) {
            alert("Please select atleast " + atLeast + " item(s)");
            return false;
        }
        return true;
    }
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    <asp:CheckBoxList ID="CheckBoxList1" runat="server">
<asp:ListItem Text = "Apple" Value = "1"></asp:ListItem>
    <asp:ListItem Text = "Mango" Value = "2"></asp:ListItem>
    <asp:ListItem Text = "Orange" Value = "3"></asp:ListItem>
</asp:CheckBoxList>
<asp:CustomValidator ID="CustomValidator2" runat="server" ErrorMessage="*Required"
ClientValidationFunction = "ValidateCheckBoxList"></asp:CustomValidator>
<asp:Button ID="Button1" runat="server" Text="Button" />
    </div>
    </form>
</body>
</html>

0 comments:

Post a Comment