• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 199
  • Last Modified:

Select corresponding radio button by value

I set a (var rbtVal) in global and would like to automatically check
the corresponding radio button in the form onLoad

smtng like:
function setRbtEcho()
  var thisRbtn;

for (i=0;i<3;i++)
//I don't know how to loop trough the getElementById for radio buttons
if (document.getElementById('myRadioButtonEcho'[i]).value = rbtVal)


<body onLoad="setRbtEcho();">
<input type="radiobutton" id="myRadioButtonEcho" value="2b">
<input type="radiobutton" id="myRadioButtonEcho" value="3c">
<input type="radiobutton" id="myRadioButtonEcho" value="4e">
1 Solution
You can't loop through getElementById, because only one element is allowed to have it at a time.  It's unique.  You need something like getElementByTagName.  You could also youse getElementsByName.  It depends on if you want the radio buttons to have the same name(grouping) or not.

function setRbtEcho() {
var rbtVal = '3c';
inputs = document.getElementsByTagName('input');
for(var i=0; i < inputs.length; i++) {
        if(inputs[i].type == 'radio') {
               if(inputs[i].value == rbtVal) {
                        inputs[i].checked = true;

<body onLoad="setRbtEcho();">
<input type="radio" id="myRadioButtonEcho" value="2b">
<input type="radio" id="myRadioButtonEcho" value="3c">
<input type="radio" id="myRadioButtonEcho" value="4e">
JoeUSAuthor Commented:

Thanks a lot for the info on the getElementById and for the example.
I ended up using the getElementsByName
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now