Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 567
Propeller Avatar asked Mar 05 '12 04:03

Propeller


People also ask

How do you find the value of a radio button group?

To get the value of selected radio button, a user-defined function can be created that gets all the radio buttons with the name attribute and finds the radio button selected using the checked property. The checked property returns True if the radio button is selected and False otherwise.

What is the value of a radio button?

Radio buttons don't participate in constraint validation; they have no real value to be constrained.


2 Answers

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

document.querySelector('input[name="gender"]:checked').value 
like image 188
darelf Avatar answered Oct 16 '22 13:10

darelf


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.

like image 37
Anthony Avatar answered Oct 16 '22 12:10

Anthony