Wednesday 1 March 2023

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

Below is the code for Validating RedioButton List to to check if selected using JavaScript in .net application.
 
In this code, we first select all the radio buttons with the name rdblList using getElementsByName. We then loop through each radio button and check if it is checked. If we find a radio button that is checked, we set the isSelected variable to true and break out of the loop. Finally, we use the isSelected variable to determine whether a radio button is selected or not, and display an error message if no radio button is selected.


-----------------------------------

<%@ 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 type="text/javascript">    

        function validate() {
            var radioButtons = document.getElementsByName('rdblList');
            var isSelected = false;

            for (var i = 0; i < radioButtons.length; i++) {
                if (radioButtons[i].checked) {
                    isSelected = true;
                    break;
                }
            }

            if (isSelected == false) {
                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>

0 comments:

Post a Comment

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