[javascript] Checking Value of Radio Button Group via JavaScript?

This may seem silly and downright stupid but I can't seem to figure out how to check the value of a radio button group in my HTML form via JavaScript. I have the following code:

<input type="radio" id="genderm" name="gender" value="male" />
<label for="genderm">Male</label>
<input type="radio" id="genderf" name="gender" value="female" />
<label for="genderf">Female</label>

How do I retrieve the value of gender via JavaScript?

This question is related to javascript html forms radio-button

The answer is


If you are using a javascript library like jQuery, it's very easy:

alert($('input[name=gender]:checked').val());

This code will select the checked input with gender name, and gets it's value. Simple isn't it?

Live demo


If you wrap your form elements in a form tag with a name attribute you can easily get the value using document.formName.radioGroupName.value.

<form name="myForm">
    <input type="radio" id="genderm" name="gender" value="male" />
    <label for="genderm">Male</label>
    <input type="radio" id="genderf" name="gender" value="female" />
    <label for="genderf">Female</label>
</form>

<script>
    var selected = document.forms.myForm.gender.value;
</script>

To get the value you would do this:

document.getElementById("genderf").value;

But to check, whether the radio button is checked or selected:

document.getElementById("genderf").checked;

In pure Javascript:

var genders = document.getElementsByName("gender");
var selectedGender;

for(var i = 0; i < genders.length; i++) {
   if(genders[i].checked)
       selectedGender = genders[i].value;
 }

update

In pure Javascript without loop, using newer (and potentially not-yet-supported) RadioNodeList :

var form_elements = document.getElementById('my_form').elements;
var selectedGender = form_elements['gender'].value;

The only catch is that RadioNodeList is only returned by the HTMLFormElement.elements or HTMLFieldSetElement.elements property, so you have to have some identifier for the form or fieldset that the radio inputs are wrapped in to grab it first.


Try:


var selectedVal;

for( i = 0; i < document.form_name.gender.length; i++ )
{
  if(document.form_name.gender[i].checked)
    selectedVal = document.form_name.gender[i].value; //male or female
    break;
  }
}


_x000D_
_x000D_
function myFunction() {_x000D_
document.getElementById("text").value='male'_x000D_
 document.getElementById("myCheck_2").checked = false;_x000D_
  var checkBox = document.getElementById("myCheck");_x000D_
  var text = document.getElementById("text");_x000D_
  if (checkBox.checked == true){_x000D_
    text.style.display = "block";_x000D_
  } else {_x000D_
     text.style.display = "none";_x000D_
  }_x000D_
}_x000D_
function myFunction_2() {_x000D_
document.getElementById("text").value='female'_x000D_
 document.getElementById("myCheck").checked = false;_x000D_
  var checkBox = document.getElementById("myCheck_2");_x000D_
  var text = document.getElementById("text");_x000D_
  if (checkBox.checked == true){_x000D_
    text.style.display = "block";_x000D_
  } else {_x000D_
     text.style.display = "none";_x000D_
  }_x000D_
}
_x000D_
Male: <input type="checkbox" id="myCheck"  onclick="myFunction()">_x000D_
Female: <input type="checkbox" id="myCheck_2"  onclick="myFunction_2()">_x000D_
_x000D_
<input type="text" id="text" placeholder="Name">
_x000D_
_x000D_
_x000D_


Use document.querySelector() if you want to avoid frameworks (which I almost always want to do).

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

Without loop:

document.getElementsByName('gender').reduce(function(value, checkable) {
    if(checkable.checked == true) 
        value = checkable.value; 
    return value;
}, '');

reduce is just a function that will feed sequentially array elements to second argument of callback, and previously returned function to value, while for the first run, it will use value of second argument.

The only minus of this approach is that reduce will traverse every element returned by getElementsByName even after it have found selected radio button.


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 forms

How do I hide the PHP explode delimiter from submitted form results? React - clearing an input value after form submit How to prevent page from reloading after form submit - JQuery Input type number "only numeric value" validation Redirecting to a page after submitting form in HTML Clearing input in vuejs form Cleanest way to reset forms Reactjs - Form input validation No value accessor for form control TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

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