Bagzli
Bagzli

Reputation: 6577

ASP.NET Select RadioButtonList value with JavaScript

I've been trying to figure this out for hours, but with now luck. Was hoping you can help me. here is my script:

function confirmPurge() {
        var d = confirm("You are about to purge all records, click Ok to proceed");
        if (d) {
            var c = document.getElementByName("yes");
            c.checked = true;
        }
        else {
            var c = document.getElementByName("no");
            c.checked = true;
        }

and html is this:

<asp:RadioButtonList ID="rblPurgeRecords" runat="server" 
                    RepeatDirection="Horizontal">
                    <asp:ListItem onclick="confirmPurge();" name="yes">Yes</asp:ListItem>
                    <asp:ListItem Selected="True" name="no">No</asp:ListItem>
                </asp:RadioButtonList>

When I try to run it, i get a pop up asking me to click ok or cancel. If I click ok my code breaks and I get this error: "Microsoft JScript runtime error: 'ScriptManager' is undefined"

Was wondering why is this not working? or is there a better way to programatically set which button in radio list is selected.

Upvotes: 3

Views: 10430

Answers (2)

Vikas
Vikas

Reputation: 50

I was also facing same problem but fortunately found one solution. Code for the same is below

function test() {
var rad = document.getElementById('<%=rblPurgeRecordse.ClientID %>');
var radio = rad.getElementsByTagName("input");
for (var i=0;i<radio.length;i++){
       if (radio[i].checked)
       {
           //your Code goes here....
           alert("SelectedValue = " + radio[i].value);
       }
    }
}

Upvotes: 3

Jack Marchetti
Jack Marchetti

Reputation: 15754

You want to get the value of the actual radiobutton not the list item. And remember that the ID of the radiubotton you assign in the .NET control isn't the actual ID on the rendered page so you'll need to use the ClientID.

var radios = document.getElementsByName('<% rblPurgeRecords.ClientID %>');

for (var i = 0, length = radios.length; i < length; i++) {
    if (radios[i].checked) {
        // do whatever you want with the checked radio
        // the value of the radio button is : radios[i].value);

        break;
    }
}

Upvotes: 0

Related Questions