How to get the selected radio button’s value?

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:


Male
Female

Search

Solutions/Answers:

Solution 1:

JavaScript:

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

http://jsfiddle.net/Xxxd3/610/

Edit: Thanks HATCHA and jpsetung for your edit suggestions.

Solution 2:

This works with any explorer.

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

It is the purest way to get the value of any input type.
You also do not need to include jQuery path.

Related:  Use of the JavaScript 'bind' method

Solution 3:

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

Solution 4:

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

Solution 5:

The simplest solution:

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

Solution 6:

ECMAScript 6 version

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