Wednesday, 1 March 2023

Validate CheckboxList to select at least one item using jQuery in .net application

Below is the code for Validating Checkbox List to select at least one item using jQuery in .net application.

In this code, we use a jQuery selector $('#chklist input[type=checkbox]:checked') to select all the checkboxes under the chklist table that are checked. We then use the .length property to check if the selected checkboxes length is greater than zero. If the length is zero then we display an error message.
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Test.aspx.vb" Inherits="Test" ValidateRequest="false" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head runat="server">
    <title>Validate Chackbox list</title>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script type="text/javascript">    

        function validate() {
            if ($('#chklist input[type=checkbox]:checked').length > 0) {
                    alert("Please select at least one item from checkbox list.");
                    return false;
                }
        }
    </script>

</head>

<body style="margin: 0;">
    <form id="frmHome" method="post" runat="server">
        <table id="Table1" style="width: 100%" cellspacing="0" cellpadding="0" border="0">
            <tr>
                <td align="center" valign="top" style="width: 100%;">

                    <asp:CheckBoxList runat="server" ID="chklist">
                        <asp:ListItem>Validate 1</asp:ListItem>
                        <asp:ListItem>Validate 2</asp:ListItem>
                        <asp:ListItem>Validate 3</asp:ListItem>
                        <asp:ListItem>Validate 4</asp:ListItem>
                    </asp:CheckBoxList>

                    <br />
                    <br />
                    <asp:Button runat="server" ID="btnval" Text="Validate" OnClientClick="return validate();" />
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

 

 

0 comments:

Post a Comment

Please do not enter any spam link in the message box.