How can we access the value of a radio button using the DOM?
Asked Answered
N

12

16

How can we access the value of a radio button using the DOM?

For eg. we have the radio button as :

<input name="sex" type="radio" value="male">

<input name="sex" type="radio" value="female">

They are inside a form with name form1. When I try

document.getElementByName("sex").value

it returns 'male' always irrespective of the checked value.

Nitwit answered 2/3, 2009 at 21:51 Comment(0)
G
21

Just to "generify" Canavar's very helpful function:

function getRadioValue(theRadioGroup)
{
    var elements = document.getElementsByName(theRadioGroup);
    for (var i = 0, l = elements.length; i < l; i++)
    {
        if (elements[i].checked)
        {
            return elements[i].value;
        }
    }
}

... which would now be referenced thusly:

getRadioValue('sex');

Strange that something like this isn't already a part of prototype.js.

Gravitt answered 16/11, 2010 at 17:15 Comment(2)
+1 It is probably better, though, (performance-wise) to call document.getElementsByName only once (instead of N+2 times) and assign it to a local variable outside of the loop.Medlin
This was probably the best way to do it 6+ years ago. But we now have document.querySelector and a powerful CSS Selector syntax, which can be utilized with much less code. jsperf examples between getElementsByName and a for loop, versus document.querySelector, might show one method being more efficient than the other on some browsers, but probably only matters if you're doing 100k+ calls, and so generally negligible performance difference.Hearttoheart
T
16

Surprised no-one has suggested actually using the Selector API:

document.querySelector('input[name=sex]:checked').value

Browser support is good

Treva answered 28/10, 2016 at 14:50 Comment(2)
Ah, just noticed this comment at the end. Added my comment above, referenced the MDN reference for method usage, and W3Schools for selector syntax. Combine that with your link for browser support, and people should be in good shape here. If you don't want to use a framework, just use document.querySelector. Also check out a more complete list of CSS Selector Syntax.Hearttoheart
And it works if the radio buttons are outside a form as well. Thank you kindly.Reliquiae
I
8

If you need the selected one, most frameworks support functionality like this:

//jQuery
$("input[name='sex']:checked").val()
Intercalation answered 2/3, 2009 at 21:58 Comment(2)
Surely it should be ‘:checked’? Also note it is possible for neither radio button to be selected in which case the val() call will fail.Quintero
If you don't want to use a framework, just use document.querySelector. Also check out a more complete list of CSS Selector Syntax.Hearttoheart
A
7

There are a couple of ways.

1. Put an id on each input

<input name="sex" id="sex_male" type="radio" value="male">
<input name="sex" id="sex_female" type="radio" value="female">

Then you can use document.getElementById("sex_male")

2. Use something like PrototypeJS (jQuery works too)

Then you can do something like this:

//This loops over all input elements that have a name of "sex"
$$('input[name="sex"]').each( function(elem) {
  //Do something
});

Or even this to get at just the "male" radio button:

$$('input[name="sex"][value="male"]').each(function(elem) {
  //Do something
});

An easy way to get started with Prototype is include it from Google by adding this between the <head></head> tags of your page:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.3/prototype.js"></script>
Approbate answered 2/3, 2009 at 21:53 Comment(0)
C
7

You can get your selected radio's value by this method :

<script>
function getRadioValue()
{
    for (var i = 0; i < document.getElementsByName('sex').length; i++)
    {
        if (document.getElementsByName('sex')[i].checked)
        {
            return document.getElementsByName('sex')[i].value;
        }
    }
}
</script>
Claudy answered 2/3, 2009 at 22:0 Comment(0)
C
2

If you want the selected one, but don't have a framework handy, you can iterate over the element array looking for whichever one is checked:

for (var i = 0; i < document.form1.sex.length; i++) {
    if (document.form1.sex[i].checked) alert(document.form1.sex[i].value);
}
Clamper answered 2/3, 2009 at 22:1 Comment(0)
T
1

If you use document.form1.sex, you are returned an array.

document.form1.sex[0] = first radio button

document.form1.sex[1] = second radio button

To check which is checked you need to loop:

whoChecked(document.form1.sex)

function whoChecked(fieldName) {
   for(var x=0;x<fieldName.length;x++) {
     if(fieldName[x].checked) {
        return fieldname[x].value
     }
}
Tyratyrannical answered 2/3, 2009 at 21:56 Comment(2)
While this approach certainly works, I find it be kind of fragile. There end up being a lot of things that you have to remember to change if you rename your form or change the order of the HTML elements.Approbate
For those who will try to use this code: in return should be "fieldName" instead of "fieldname". It causes JS errorCelibacy
E
1
var list = document.getElementsByName('sex');
for(var i=0;i<list.length;i++){
   if(list[i].type=='radio' && list[i].checked){
      alert(list[i].value);
      break;
   }
}
Enfield answered 2/3, 2009 at 21:59 Comment(0)
Q
1
document.getElementByName("sex").value

You mean getElementsByName('sex')[0].value? (There's no getElementByName.)

That will of course always pick the first input element with that name — the one whose value is indeed male. You then check to see if it's selected by using the ‘.checked’ property.

For this simple case you can get away with:

var sex= document.getElementsByName("sex")[0].checked? 'male' : 'female';

For the general case you have to loop over each radio input to see which is checked. It would probably be better to get the form object first (putting an id on the form and using document.getElementById is generally better than using the ‘name’-based document.forms collection), and then access form.elements.sex to get the list, in case there are any other elements on the page that have name="sex" attributes (potentially other things than form fields).

Quintero answered 2/3, 2009 at 22:0 Comment(0)
E
0
function getEleByName(){
    if(true==document.getElementsByName('gender')[0].checked){
        alert('selected gender is: male');
    }
    else{
        alert('selected gender is: female');
    }
}
Eikon answered 28/8, 2017 at 15:56 Comment(0)
S
-1

Loops can achieve the task, as others have shown but it could be simpler than using a loop, which will help performance if desired. Also, it can be portable/modular so it can be used for different radio groups.

Simple Example

function getValue(x) {
  alert(x.value);
}
<input name="sex" type="radio" value="male" onChange="getValue(this)" />
<input name="sex" type="radio" value="female" onChange="getValue(this)" />

A more complex example:

function getValue(x){
  alert(x.value);
}
<fieldset>
  <legend>Sex</legend>
  <label>Male:
    <input name="sex" type="radio" value="male" onChange="getValue(this)"/>
  </label>
  <label>Female:
    <input name="sex" type="radio" value="female" onChange="getValue(this)" />
  </label>
</fieldset>
<fieldset>
  <legend>Age Group</legend>
  <label>0-13:
    <input name="ageGroup" type="radio" value="0-13" onChange="getValue(this)" />
  </label>
  <label>13-18:
    <input name="ageGroup" type="radio" value="13-18" onChange="getValue(this)" />
  </label>
  <label>18-30:
    <input name="ageGroup" type="radio" value="13-18" onChange="getValue(this)" />
  </label>
  <label>30+:
    <input name="ageGroup" type="radio" value="13-18" onChange="getValue(this)" />
  </label>
</fieldset>
Snoopy answered 23/9, 2015 at 20:42 Comment(0)
D
-1
  • document.all.sex[0].checked
  • document.all.set[1].checked
Dumfound answered 11/8, 2016 at 14:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.