In JavaScript, how can I get all radio buttons in the page with a given name?
Asked Answered
F

9

18

Like the title says, what's the best way in JavaScript to get all radio buttons on a page with a given name? Ultimately I will use this to determine which specific radio button is selected, so another way to phrase the question:

Given a string variable in JavaScript, how can I tell which exact radio button input element (if any) with that string as it's name is currently selected?

I'm not using jQuery. If you want to provide a jQuery answer, go ahead. Someone else might find it useful. But it won't help me and I won't upvote it.

Fragonard answered 5/11, 2009 at 19:29 Comment(3)
I know it is. I've written about it at length: #149170 But it's not up to me.Fragonard
Wow, it's a good thing that link to Wikipedia/Javascript was added because I was totally clueless!Pokey
@Peter Mortensen: getting a little happy on the edit trigger there aren't ya?Jawbreaker
P
30

You can use document.getElementsByName(), passing the name of the radio group, then loop over them inspecting the checked attribute, e.g. something like:

function getCheckedValue( groupName ) {
    var radios = document.getElementsByName( groupName );
    for( i = 0; i < radios.length; i++ ) {
        if( radios[i].checked ) {
            return radios[i].value;
        }
    }
    return null;
}
Priscian answered 5/11, 2009 at 19:34 Comment(5)
This potentially includes <input type="checkbox" /> with the same name.Unshapen
Hmm... I was thinking this couldn't work because of the checkboxes. That was kind of the main problem. But I realize now I can add an expression to the if condition to filter them out by tagname, so this should work for me.Fragonard
@Joel: I think you meant filter them out by type. Tagnames would be the same "input".Unshapen
Checkboxes with the same name attribute are going to screw up the form submission anyways, so I wouldn't worry about it.Pokey
getElementsByName vs getElementByName what a croc.Coffin
T
10

getElementsByName didn't work for me. I did this:

    var radios = document.getElementsByTagName('input');
    for (i = 0; i < radios.length; i++) {
        if (radios[i].type == 'radio' && radios[i].checked) {
            nbchecked++;
        }
    }
Trumaine answered 21/3, 2011 at 11:47 Comment(0)
N
8

Use document.getElementsByName() is the short answer to the question you asked.

However, it may be better to do something like this:

<form name="formFoo">
  Foo: <input type="radio" name="groupFoo" value="foo" checked> <br />
  Bar: <input type="radio" name="groupFoo" value="bar"> <br />
  Baz: <input type="radio" name="groupFoo" value="baz"> <br />
  <input type="submit" >
</form> 

Then use the JavaScript:

function getRadioValue(formName, groupName) {
    var radioGroup = document[formName][groupName];
    for (var i=0; i<radioGroup.length; i++)  {
       if (radioGroup[i].checked)  {
       return radioGroup[i].value;
       }
    }
    return null;
}

By doing this, you avoid having to use a function that searches the entire document. It just searches first for the form, then within that form for controls with that same name. The problem here is that if you were to have a checkbox in the middle of the form with the same name, it could be returned instead of the correct radio value. If another type of control was thrown in with the same name, then it could cause an error. Both of these circumstances should probably be considered programmer error, but it wouldn't hurt for the function to be expanded to check for them, at some potential performance loss. Just change the line:

       if (radioGroup[i].checked)  {

to:

       if (radioGroup[i].type=='radio' && radioGroup[i].checked)  {
Needless answered 5/11, 2009 at 19:35 Comment(2)
I think document.form.groupFoo[i].value should be document.formFoo.groupFoo[i].value.Akela
@Phaedrus, I revised the entire function, and actually tested it this time, but you were right.Needless
N
4

I'll bite for the jQuery answer

var selectedValue = $("input[name='radio_name']:checked").val();
Nairn answered 5/11, 2009 at 19:36 Comment(0)
A
3
var options = document.getElementsByName('myRadioButtons');
for(i = 0; i < options.length; i++)
{
    var opt = options[i];
    if(opt.type=="radio")
    {              
        if(opt.checked)
        {
        }                  
    }
}
Akela answered 5/11, 2009 at 19:35 Comment(0)
C
2
<form name="myForm" id="myForm" action="">  
<input type="radio" name="radioButton" value="c1">Choice 1
<input type="radio" name="radioButton" value="c2">Choice 2
</form>
<script>
var formElements = window.document.getElementById("myForm").elements;
var formElement;
var radioArray = [];

for (var i = 0, j = 0; i < formElements.length; i++) {
    formElement = formElements.item(i);
    if (formElement.type === "radio" && formElement.name === "radioButton") {
        radioArray[j] = formElement;
        ++j;
    }
}
alert(radioArray[0].value);
alert(radioArray[1].value);
</script>
Collectivism answered 5/11, 2009 at 19:58 Comment(0)
J
0
$("input[type='radio'][name='xxxxx']:checked").val()
Judaica answered 5/11, 2009 at 19:38 Comment(0)
T
0

To get all radio buttons directly by name:

element.querySelectorAll("input[name='nameOfTheName']")

The querySelectorAll() method can be used to get elements of a certain type by name. There are advantages to using querySelectorAll compared to getElementsByName() in certain situations. If you use getElementsByName on anything other than document, you will get an error:

element_Name_Here.getElementsByName is not a function

But querySelectorAll() can be used on sub elements of the document. This is helpful when you want to get one element out of multiple elements that all have the same structure (Rows in a list). In that case, you might not want to try to give separate ID's to every row. In that situation, the function called can be passed this, get the parentNode and from the parent, search for a specific attribute. This avoids needing to search the entire document.

html

<div>
  <input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
  <input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
  <input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
</div>
<div>
  <input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
  <input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
  <input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
</div>
<div>
  <input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
  <input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
  <input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
</div>
<div>
  <input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
  <input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
  <input type="radio" name="nameOfName" onchange="getOnlyThisRowsRadios(this)">
</div>

script

function getOnlyThisRowsRadios(thiz) {
  var i,L,parentElement,radioButtons;

  parentElement = thiz.parentNode;//Get the parent of the element
  radioButtons = parentElement.querySelectorAll("input[name='nameOfTheName']");
  console.log('radioButtons: ' + radioButtons)

  L = radioButtons.length;
  console.log('L: ' + L)

  for (i=0;i<L;i++) {
    console.log('radBttns[i].checked: ' + radBttns[i].checked)
    radBttns[i].checked = false;//Un-check all checked radios
  }
Trefor answered 8/3, 2017 at 21:3 Comment(0)
D
-1

This definitely works if your name attribute is taken for something else.

var radios = document.getElementsByTagName('input');

 for (i = 0; i < radios.length; i++) {
    if (radios[i].type == 'radio' && radios[i].checked) {
console.log(radios[i])
    }
}
Dread answered 15/1, 2021 at 7:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.