Search code examples
c#javascriptasp.netradiobuttonlist

ASP.net getting RadioButtonList value on content page with javascript


I'm having a problem with my JavaScript code having moved it over to a content page in ASP.

It worked perfectly on a stand alone page.

<script type="text/javascript">
        function validateQ12(oSrc, args) {
            var rbtnList = document.getElementsByName('rbtn12');
            var noClicked = false;
            for (var i = 0; i < rbtnList.length; i++) {
                if (rbtnList[i].checked) {
                    noClicked = rbtnList[i].value == "No";
                    break;
                }
            }
            if (noClicked) {
                args.IsValid = true;                   
            }
            else
                args.IsValid = args.Value.trim().length > 0;                   
        }
    </script> 

I have gone through the html on both pages, on the one that worked had

<input id="rbtn12_1" type="radio" name="rbtn12" value="No" checked="checked" onclick="Q12iNo();">

The new one inside a content page has

<input id="MainContent_rbtn12_1" type="radio" name="ctl00$MainContent$rbtn12" value="No" checked="checked" onclick="Q12iNo();">

Clearly the name change must be causing the problem. How do I reference this new name in my javascript code?


Solution

  • To get the rendered element name use the following:

    <%= rbtn12.UniqueID %>
    

    However in your case this may still not work as it looks like you need to loop through each radio button item.

    See the following post:

    Find out if radio button is checked with JQuery?

    Which shows how to determine if a radio button collection has a selected value.