Monday, July 1, 2013

Javascript validation for asp.net radiobutton


HTML:
<asp:RadioButton Text="Male" runat="server" ID="rbMale" GroupName="m" />

<asp:RadioButton Text="Female" runat="server" ID="rbFemale" GroupName="m" />

<br />
 <asp:Button Text="Submit" ID="btn" runat="server" OnClientClick="return Validate()"
 />

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

Rendering of RadioButtons:

<input id="MainContent_rbMale" type="radio" name="ctl00$MainContent$m" value="rbMale">
<label for="MainContent_rbMale">Male</label>


<input id="MainContent_rbFemale" type="radio" name="ctl00$MainContent$m" value="rbFemale">
<label for="MainContent_rbFemale">Female</label>


Javascript:

<script type="text/javascript">

        function Validate() {

            var rbM = document.getElementById("<%=rbMale.ClientID %>");
            var rbF = document.getElementById("<%=rbFemale.ClientID %>");
           

            if (rbM.checked) {
                document.getElementById("spn").innerHTML = "You have selected: " + rbM.nextSibling.innerHTML;
                return false;
            }
            else if (rbF.checked) {

                document.getElementById("spn").innerHTML = "You have selected: " + rbF.nextSibling.innerHTML;
                return false;
            }
            else {
                alert("Please select Gender!");
                return false;
            }

            return true;
        }
    </script>