[javascript] How to get the selected radio button’s value?

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>

This question is related to javascript html for-loop radio-button

The answer is


    var value = $('input:radio[name="radiogroupname"]:checked').val();

Using a pure javascript, you can handle the reference to the object that dispatched the event.

function (event) {
    console.log(event.target.value);
}

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


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 @).


 <input type=radio name=rdbExampleInfo id=rdbExamples value="select 1">
 <input type=radio name=rdbExampleInfo id=rdbExamples value="select 2">
 <input type=radio name=rdbExampleInfo id=rdbExamples value="select 3">
 <input type=radio name=rdbExampleInfo id=rdbExamples value="select 4"> 

etc then use just

  $("#rdbExamples:checked").val()

Or

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

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.


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.


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

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 : http://bloggerplugnplay.blogspot.in/2013/01/validateget-checked-radio-value-in.html


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.


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


document.forms.your-form-name.elements.radio-button-name.value

ECMAScript 6 version

let genderS = Array.from(document.getElementsByName("genderS")).find(r => r.checked).value;

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.


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.


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

document.forms['form_name']['input_name'].value;

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);

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">

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to for-loop

List append() in for loop Prime numbers between 1 to 100 in C Programming Language Get current index from foreach loop how to loop through each row of dataFrame in pyspark TypeScript for ... of with index / key? Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply? Python for and if on one line R for loop skip to next iteration ifelse How to append rows in a pandas dataframe in a for loop? What is the difference between ( for... in ) and ( for... of ) statements?

Examples related to radio-button

Angular 4 default radio button checked by default Angular2 - Radio Button Binding Detect if a Form Control option button is selected in VBA How to create radio buttons and checkbox in swift (iOS)? How to check if a radiobutton is checked in a radiogroup in Android? Radio Buttons ng-checked with ng-model Multiple radio button groups in MVC 4 Razor Show div when radio button selected Check a radio button with javascript Bootstrap radio button "checked" flag