377

I’m having some strange problem with my JS program. I had this working properly but for some reason it’s no longer working. I just want to find the value of the radio button (which one is selected) and return it to a variable. For some reason it keeps returning undefined.

Here is my code:

function findSelection(field) {
    var test = 'document.theForm.' + field;
    var sizes = test;

    alert(sizes);
        for (i=0; i < sizes.length; i++) {
            if (sizes[i].checked==true) {
            alert(sizes[i].value + ' you got a value');     
            return sizes[i].value;
        }
    }
}

submitForm:

function submitForm() {

    var genderS =  findSelection("genderS");
    alert(genderS);
}

HTML:

<form action="#n" name="theForm">

    <label for="gender">Gender: </label>
    <input type="radio" name="genderS" value="1" checked> Male
    <input type="radio" name="genderS" value="0" > Female<br><br>
    <a href="javascript: submitForm()">Search</A>
</form>
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
mkyong
  • 12,497
  • 12
  • 37
  • 56
  • 1
    Possible duplicate of [How to get the selected radio button value using js](http://stackoverflow.com/questions/3869535/how-to-get-the-selected-radio-button-value-using-js) – Damjan Pavlica Sep 26 '16 at 14:40

19 Answers19

560

This works with any explorer.

document.querySelector('input[name="genderS"]:checked').value;

This is a simple way to get the value of any input type. You also do not need to include jQuery path.

Giorgos Tsakonas
  • 5,845
  • 3
  • 17
  • 20
  • 28
    Using document.querySelector() is a pure javascript answer: https://developer.mozilla.org/en-US/docs/Web/API/document.querySelector – AdamJonR Feb 09 '15 at 06:05
  • 9
    If you store it in a variabel and no radiobutton is selected you cause the browser to stop. Console says: TypeError `document.querySelector(...)` is `null`. – call-me May 23 '15 at 22:44
  • 23
    That does only work if one is selected. So you should check it before. `var selector = document.querySelector('input[name="genderS"]:checked'); if(selector) console.log(selector.value);` – Markus Zeller Dec 10 '15 at 15:58
  • I'm working with Templates in Meteor,and that `:checked` trick totally nailed it for me.. for me the fix to reading radio buttons from a Meteor Template form was `accountType = template.find("[name='optradio']:checked").value;` – zipzit Aug 23 '16 at 07:11
  • I have one enterprise environment where it does not work consistently on IE11 - some kind of backwards compatability mode. – Steve Black May 06 '18 at 23:44
  • @jgomo3 If you check the date, actually the answer you link was done two *years* after this one. Giorgos is from 2014, alluma is from 2016. – Félix Adriyel Gagnon-Grenier Nov 14 '18 at 19:42
  • What is the one liner for returning empty if nothing is selected (i.e the selector returns nothing) – mplungjan Mar 24 '20 at 11:25
  • this way doesn't work if your radios are inside labels – Igor Fomenko Jun 21 '20 at 12:46
  • And you can use it in jQuery by using:`$('input[name="genderS"]:checked').val()` – George Ogden Jun 23 '20 at 11:27
  • 1
    @markus-zeller In modern browsers you can use the chaining operator (.?) to guard for nullish, e.g. `document.querySelector('input[name="genderS"]:checked')?.value;` – Simon Jan 20 '21 at 09:46
  • @Simon That was 2015. Nobody would use `var` anymore. – Markus Zeller Jan 20 '21 at 12:59
450

You can do something like this:

var radios = document.getElementsByName('genderS');

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

    // only one radio can be logically checked, don't check the rest
    break;
  }
}
<label for="gender">Gender: </label>
<input type="radio" name="genderS" value="1" checked="checked">Male</input>
<input type="radio" name="genderS" value="0">Female</input>

jsfiddle

Edit: Thanks HATCHA and jpsetung for your edit suggestions.

A1rPun
  • 16,287
  • 7
  • 57
  • 90
jbabey
  • 45,965
  • 12
  • 71
  • 94
  • 7
    That was working for jquery 1.7 but now the correct syntax for jQuery 1.9 is $('input[name="genderS"]:checked').val(); (remove the @) – jptsetung Jun 04 '13 at 15:19
  • 1
    I believe the `@` syntax was [deprecated even earlier](http://api.jquery.com/category/selectors/attribute-selectors/) than that (jquery 1.2) – Tom Pietrosanti Jun 21 '13 at 12:24
  • @TomPietrosanti the documentation appears to be a little off, http://jsfiddle.net/Xxxd3/608/ works in <1.7.2 but not in >1.8.3. Regardless, the `@` should definitely be removed – jbabey Jun 21 '13 at 12:28
  • Yeah, it looks like they left some backwards compatibility in there, but didn't update the docs to match. I remember some hoopla when they dropped some deprecated features that were still widely in use, so they added support back in. Maybe that's why... – Tom Pietrosanti Jun 21 '13 at 12:41
  • I like your use of `length` here. It's like the future's built in. – Lori Jun 30 '14 at 22:31
  • 6
    [`document.querySelector()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector) should probably be the recommended approach in straight JavaScript now. – Dave Nov 03 '15 at 16:54
  • You guys all have 1 form on a document? – Joeri Jul 12 '18 at 10:40
  • for...of is supported by all modern browsers, and is a little easer to read / understand. so `for (let radio of radios) { \\do stuff }` – brandonmack May 10 '21 at 20:19
  • `const checkedRadio = radios.find(({ checked }) => checked);` will get the first (and only, in this case) input with truthy `checked`. If there is a chance that none is checked, you'll want to make sure that `checkedRadio` is not null. – pr-shadoko Apr 20 '22 at 09:47
63
document.forms.your-form-name.elements.radio-button-name.value
bluish
  • 26,356
  • 27
  • 122
  • 180
imran ansari
  • 685
  • 5
  • 2
  • 9
    This works too: `document.forms.your-form-name.name-shared-by-radio-buttons.value` – Web_Designer Nov 25 '15 at 00:51
  • 14
    I think most people are overlooking this. The accepted answer works. Giorgos Tsakonas answer is better. But this one is the fundamentally correct answer. This one is how radio buttons actually work. Note that if nothing has been selected, it returns an empty string. – Mark Goldfain May 20 '18 at 20:46
32

Since jQuery 1.8, the correct syntax for the query is

$('input[name="genderS"]:checked').val();

Not $('input[@name="genderS"]:checked').val(); anymore, which was working in jQuery 1.7 (with the @).

jptsetung
  • 9,064
  • 3
  • 43
  • 55
24

ECMAScript 6 version

let genderS = Array.from(document.getElementsByName("genderS")).find(r => r.checked).value;
Nappy
  • 3,016
  • 27
  • 39
11

Here's a nice way to get the checked radio button's value with plain JavaScript:

const form = document.forms.demo;
const checked = form.querySelector('input[name=characters]:checked');

// log out the value from the :checked radio
console.log(checked.value);

Source: https://ultimatecourses.com/blog/get-value-checked-radio-buttons

Using this HTML:

<form name="demo">
  <label>
    Mario
    <input type="radio" value="mario" name="characters" checked>
  </label>
  <label>
    Luigi
    <input type="radio" value="luigi" name="characters">
  </label>
  <label>
    Toad
    <input type="radio" value="toad" name="characters">
  </label>
</form>

You could also use Array Find the checked property to find the checked item:

Array.from(form.elements.characters).find(radio => radio.checked);
Rachie M
  • 111
  • 1
  • 2
10

In case someone was looking for an answer and landed here like me, from Chrome 34 and Firefox 33 you can do the following:

var form = document.theForm;
var radios = form.elements['genderS'];
alert(radios.value);

or simpler:

alert(document.theForm.genderS.value);

refrence: https://developer.mozilla.org/en-US/docs/Web/API/RadioNodeList/value

ashraf aaref
  • 189
  • 2
  • 10
  • I really guess this is the preferred way to go today. One might however also select the form via `querySelector`, which works fine too: `const form = document.querySelector('form[name="somename"]')`. Also one can set the value of `radios` with `radios.value = {value}` However, selecting the radios directly (e.g. `document.querySelectorAll('input[name="some_radio"]')`) will *not* work, because it returns `NodeList` instead of `RadioNodeList`. This is why you have to select the form first. – ptmr.io Dec 31 '20 at 10:38
8

Edit: As said by Chips_100 you should use :

var sizes = document.theForm[field];

directly without using the test variable.


Old answer:

Shouldn't you eval like this ?

var sizes = eval(test);

I don't know how that works, but to me you're only copying a string.

Michael Laffargue
  • 10,116
  • 6
  • 42
  • 76
  • eval is not the best option here... you might want to say `var sizes = document.theForm[field];` and delete the first assignment, so not using `test` variable anymore. – Dennis Mar 08 '12 at 13:43
  • For my knowledge, would eval work as is? Or would it work only with `eval('var sizes=document.theForm.' + field)` ? – Michael Laffargue Mar 08 '12 at 13:53
  • the eval statement in your answer `var sizes = eval(test);` would work that way (i just testet it in firebug). – Dennis Mar 08 '12 at 13:59
  • That makes more sense, but I'm getting an error "Unexpected token [" on that line where I put `field` in brackets. Any guesses as to why? – mkyong Mar 08 '12 at 14:00
7

This is pure JavaScript, based on the answer by @Fontas but with safety code to return an empty string (and avoid a TypeError) if there isn't a selected radio button:

var genderSRadio = document.querySelector("input[name=genderS]:checked");
var genderSValue = genderSRadio ? genderSRadio.value : "";

The code breaks down like this:

  • Line 1: get a reference to the control that (a) is an <input> type, (b) has a name attribute of genderS, and (c) is checked.
  • Line 2: If there is such a control, return its value. If there isn't, return an empty string. The genderSRadio variable is truthy if Line 1 finds the control and null/falsey if it doesn't.

For JQuery, use @jbabey's answer, and note that if there isn't a selected radio button it will return undefined.

Ed Gibbs
  • 25,924
  • 4
  • 46
  • 69
7

Try this

function findSelection(field) {
    var test = document.getElementsByName(field);
    var sizes = test.length;
    alert(sizes);
    for (i=0; i < sizes; i++) {
            if (test[i].checked==true) {
            alert(test[i].value + ' you got a value');     
            return test[i].value;
        }
    }
}


function submitForm() {

    var genderS =  findSelection("genderS");
    alert(genderS);
    return false;
}

A fiddle here.

The Alpha
  • 143,660
  • 29
  • 287
  • 307
6

First, shoutout to ashraf aaref, who's answer I would like to expand a little.

As MDN Web Docs suggest, using RadioNodeList is the preferred way to go:

// Get the form
const form = document.forms[0];

// Get the form's radio buttons
const radios = form.elements['color'];

// You can also easily get the selected value
console.log(radios.value);

// Set the "red" option as the value, i.e. select it
radios.value = 'red';

One might however also select the form via querySelector, which works fine too:

const form = document.querySelector('form[name="somename"]')

However, selecting the radios directly will not work, because it returns a simple NodeList.

document.querySelectorAll('input[name="color"]')
// Returns: NodeList [ input, input ]

While selecting the form first returns a RadioNodeList

document.forms[0].elements['color']
// document.forms[0].color # Shortcut variant
// document.forms[0].elements['complex[naming]'] # Note: shortcuts do not work well with complex field names, thus `elements` for a more programmatic aproach
// Returns: RadioNodeList { 0: input, 1: input, value: "red", length: 2 }

This is why you have to select the form first and then call the elements Method. Aside from all the input Nodes, the RadioNodeList also includes a property value, which enables this simple manipulation.

Reference: https://developer.mozilla.org/en-US/docs/Web/API/RadioNodeList/value

ptmr.io
  • 2,115
  • 4
  • 22
  • 34
  • +1. Well explained. I was looking for an answer explaining the difference between using `elements` and using the shortcut variant. Thanks for that! Does the shortcut variant work on all major browsers? – Shiva Prasad Sep 27 '21 at 07:39
  • What works for me is `document.querySelector('input[name=color]:checked')`, as someone said below ` – étale-cohomology Feb 14 '22 at 06:14
3

Here is an Example for Radios where no Checked="checked" attribute is used

function test() {
var radios = document.getElementsByName("radiotest");
var found = 1;
for (var i = 0; i < radios.length; i++) {       
    if (radios[i].checked) {
        alert(radios[i].value);
        found = 0;
        break;
    }
}
   if(found == 1)
   {
     alert("Please Select Radio");
   }    
}

DEMO : http://jsfiddle.net/ipsjolly/hgdWp/2/ [Click Find without selecting any Radio]

Source (from my blog): http://bloggerplugnplay.blogspot.in/2013/01/validateget-checked-radio-value-in.html

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
Code Spy
  • 9,626
  • 4
  • 66
  • 46
3

Putting Ed Gibbs' answer into a general function:

function findSelection(rad_name) {
    const rad_val = document.querySelector('input[name=' + rad_name + ']:checked');
    return (rad_val ? rad_val.value : "");
}

Then you can do findSelection("genderS");

gaspar
  • 898
  • 1
  • 13
  • 26
2

lets suppose you need to place different rows of radio buttons in a form, each with separate attribute names ('option1','option2' etc) but the same class name. Perhaps you need them in multiple rows where they will each submit a value based on a scale of 1 to 5 pertaining to a question. you can write your javascript like so:

<script type="text/javascript">

    var ratings = document.getElementsByClassName('ratings'); // we access all our radio buttons elements by class name     
    var radios="";

    var i;
    for(i=0;i<ratings.length;i++){
        ratings[i].onclick=function(){
            var result = 0;
            radios = document.querySelectorAll("input[class=ratings]:checked");
            for(j=0;j<radios.length;j++){
                result =  result + + radios[j].value;
            }
            console.log(result);
            document.getElementById('overall-average-rating').innerHTML = result; // this row displays your total rating
        }
    }
</script>

I would also insert the final output into a hidden form element to be submitted together with the form.

Bruce Tong
  • 1,366
  • 15
  • 14
2

I like to use brackets to get value from input, its way more clear than using dots.

document.forms['form_name']['input_name'].value;
Abc Xyz
  • 1,184
  • 12
  • 13
2

I realize this is extremely old, but it can now be done in a single line

function findSelection(name) {
    return document.querySelector(`[name="${name}"]:checked`).value
}
Gustavo Shigueo
  • 399
  • 3
  • 11
1

I prefer to use a formdata object as it represents the value that should be send if the form was submitted.

Note that it shows a snapshot of the form values. If you change the value, you need to recreate the FormData object. If you want to see the state change of the radio, you need to subscribe to the change event change event demo

Demo:

let formData = new FormData(document.querySelector("form"));
console.log(`The value is: ${formData.get("choice")}`);
<form>
    <p>Pizza crust:</p>
    <p>
        <input type="radio" name="choice" value="regular" >
        <label for="choice1id">Regular crust</label>
    </p>
    <p>
        <input type="radio" name="choice" value="deep" checked >
        <label for="choice2id">Deep dish</label>
    </p>
</form>
gerardnico
  • 855
  • 11
  • 10
  • this kind of works, but it doesn't update the value whenever you select "regular crust". it only shows the default value that it loads with – greenie-beans Oct 21 '22 at 14:46
  • @greenie-beans It shows a snapshot of the form values. If you change the value, you need to recreate the `FormData` object. If you want to see the state change of the radio, you need to subscribe to the `change` event [change event demo](https://datacadamia.com/web/html/radio#event) – gerardnico Oct 29 '22 at 10:59
  • yeah. thanks for following up and sharing that. i think this answer is incomplete without that. – greenie-beans Nov 01 '22 at 15:41
0

If it is possible for you to assign a Id for your form element(), this way can be considered as a safe alternative way (specially when radio group element name is not unique in document):

function findSelection(field) {
    var formInputElements = document.getElementById("yourFormId").getElementsByTagName("input");
    alert(formInputElements);
        for (i=0; i < formInputElements.length; i++) {
        if ((formInputElements[i].type == "radio") && (formInputElements[i].name == field) && (formInputElements[i].checked)) {
            alert(formInputElements[i].value + ' you got a value');     
            return formInputElements[i].value;
        }
    }
}

HTML:

<form action="#n" name="theForm" id="yourFormId">
MMKarami
  • 1,144
  • 11
  • 14
-6
    var value = $('input:radio[name="radiogroupname"]:checked').val();