Tuesday, July 2, 2013

Javascript validation for asp.net checkboxlist

CheckBoxList
<asp:CheckBoxList ID="CBL" runat="server">
        <asp:ListItem Text="One" Value="1"></asp:ListItem>
        <asp:ListItem Text="Two" Value="2"></asp:ListItem>
        <asp:ListItem Text="Three" Value="3"></asp:ListItem>
    </asp:CheckBoxList>

JavaScript function:
<script type = "text/javascript">
function Validate()
{
   var CBL = document.getElementById("<%=RadioButtonList1.ClientID%>");
   var checkbox = CBL.getElementsByTagName("input");
   var isChecked=false;
   for (var i=0;i< checkbox.length;i++)
   {
       if (checkbox [i].checked)
       {
           isChecked=true;
           break;
       }
   }
   if(!isChecked) //or if(isChecked == false)
   {
        alert("Please select an item");
   }
   return isChecked;
}
</script>    

  
  
Getting SelectedText and SelectedValue

HTML Code
<h3>Select your Hobbies</h3>

    <asp:CheckBoxList ID="chkHobbies" runat="server"   RepeatDirection="Horizontal" RepeatColumns="4">
        <asp:ListItem Text="Collecting"></asp:ListItem>
        <asp:ListItem Text="Dancing"></asp:ListItem>
        <asp:ListItem Text="Games"></asp:ListItem>
        <asp:ListItem Text="Gardening"></asp:ListItem>
        <asp:ListItem Text="Reading"></asp:ListItem>
        <asp:ListItem Text="Sports"></asp:ListItem>
        <asp:ListItem Text="Technology"></asp:ListItem>
        <asp:ListItem Text="Writing"></asp:ListItem>
    </asp:CheckBoxList>

   
<br />

    <asp:Button Text="Submit" ID="btnHobbies" runat="server" OnClientClick="return ValidateChk()" />

<br />

    <span id="spn"></span>

Javascript function
  function ValidateChk() {

            var chk = document.getElementById("<%=chkHobbies.ClientID %>");
            var input = chk.getElementsByTagName("input");
            var text = chk.getElementsByTagName("label");
            var message = "";
            for (var i = 0; i < input.length; i++) {
                if (input[i].checked) {
                    message += text[i].innerHTML + ", ";
                }
            }
            if (message == "") {
                alert("Please select your hobby!");
            }
            else {
                document.getElementById("spn").innerHTML = "Your Hobbies are: " + message;
            }
            return false;
     }
   
Note: To get the value, we can use: message = input[i].value;