Bob Jones
Bob Jones

Reputation: 2048

How to set asp radiobuttonlist selected item in jQuery

I have two radio button lists. I want to set the selected item in jQuery when the document is fully loaded. I have function that seems to set the checked value, but doesn't actually change what shows up on the screen:

function setRadioButtonListSelected(rbl, match) {
for (var i = 0; i < rbl.length; i++) {
    if (rbl[i].value == match) {
        rbl[i].checked = true;
        break;
    }
}
}

I know how to read the value of the rbl, but I haven't been able to find any examples of how to set the selected value so that the value already rendered changes based on the match value.

Upvotes: 3

Views: 11514

Answers (2)

Orry
Orry

Reputation: 2648

This code worked for me.

Because the radio button list renders a bunch of controls you want the jquery selector to get the radio buttons only and filter out the selected radio button by the value by setting the checked property

    $( function () {
       var v = 1; // You would probably pass the selected value to a function instead 
       $('#radioButtonList[type=radio][value=' + v + ']').prop('checked', true);
    } );

Upvotes: 4

origin1tech
origin1tech

Reputation: 749

Here you go:

Note where "option" is the name value of the radios. didn't have your source html so just made it simple but you should be able to follow the jsfiddle example. Just wrap in your function and you should be good to go.

var rbl = document.getElementsByName('option');

for (var i = 0; i < rbl.length; i++) {
 if (rbl[i].value == 'two') {

    rbl[i].checked = 'checked';
    break;
  }

}

jsfiddle for you here => http://jsfiddle.net/chazelton/BpMXG/

Upvotes: 0

Related Questions