Showing posts with label Validate RadioButton List to select at least one item using jQuery. Show all posts
Showing posts with label Validate RadioButton List to select at least one item using jQuery. Show all posts

Wednesday, 1 March 2023

Validate RadioButtonList to check if selected using jQuery in .net application

Below is the code for Validating RadioButton List to to check if selected using JavaScript in .net application.

In this code, we use a jQuery selector $('#rdblList input[type=radio]:checked') to select all the radio buttons under the rdblList table that are checked. We then use the .length property to check if the selected radio buttons 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 Radio Button list</title> 
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script type="text/javascript">   
        function validate() {
            if ($('#rdblList input[type=radio]:checked').length == 0) {
                alert("Please select gender.");
                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:RadioButtonList runat="server" id="rdblList">
                        <asp:ListItem>Male</asp:ListItem>
                        <asp:ListItem>Female</asp:ListItem>
                    </asp:RadioButtonList>
                    <br />
                    <br />
                    <asp:Button runat="server" ID="btnval" Text="Validate" OnClientClick="return validate();" />
                </td>
            </tr>
        </table>
    </form>
</body>
</html>