Checking Value of Radio Button Group via JQUERY?
Asked Answered
S

9

94

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?

Sello answered 5/3, 2012 at 4:26 Comment(0)
M
66

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

Microanalysis answered 5/3, 2012 at 4:35 Comment(6)
The question was "Javascript", not "jQuery".Dictum
@MattiSG, and since it was accepted, I guess it helped the questioner(and many other people)...Microanalysis
Well, I came across this question looking for a Javascript solution, the question is not tagged jQuery, when I read the question it was not mentioning jQuery, I don't think the accepted answer should have a dependency on jQuery. But that's the power of the crowd, you know ;) My own down vote won't change much for all the many other people who you helped with this answer :)Dictum
check the answers from @Felic for pure js..!!Badr
JQuery was okay back then.Labile
i edited the question titlle as i was looking for javascript solution, not jquery so anyone else doesn't get mislead by the former tittle and BTW this avoids to downvote a correct answer regardelss that the original question was aimed to work with javascriptDurian
F
344

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

document.querySelector('input[name="gender"]:checked').value
Felic answered 18/6, 2015 at 14:20 Comment(5)
This needs more upvotes, .querySelector() is the vanilla answer to so many jQuery questions...Rabaul
This is a first, I have never before, logged in just to give someone an up vote.Cambria
@Cambria same here. Had to log in to vote this upJeb
This answer makes me sorry that the answer for a question cannot be later changed by the community or moderators. Of course, with all due respect to the chosen answer (towards both individuals involved in that decision).Tercel
I love this answer. No need for cumbersome frameworks if you know what you're doing. :-)Askja
S
105

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.

Seaway answered 5/3, 2012 at 4:36 Comment(1)
Plus one for answering the title and not providing a jQuery answer.Counterproof
M
66

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

Microanalysis answered 5/3, 2012 at 4:35 Comment(6)
The question was "Javascript", not "jQuery".Dictum
@MattiSG, and since it was accepted, I guess it helped the questioner(and many other people)...Microanalysis
Well, I came across this question looking for a Javascript solution, the question is not tagged jQuery, when I read the question it was not mentioning jQuery, I don't think the accepted answer should have a dependency on jQuery. But that's the power of the crowd, you know ;) My own down vote won't change much for all the many other people who you helped with this answer :)Dictum
check the answers from @Felic for pure js..!!Badr
JQuery was okay back then.Labile
i edited the question titlle as i was looking for javascript solution, not jquery so anyone else doesn't get mislead by the former tittle and BTW this avoids to downvote a correct answer regardelss that the original question was aimed to work with javascriptDurian
C
9

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;
Chickpea answered 5/3, 2012 at 4:35 Comment(4)
That wasn't the question. you cannot use ID here since you do not know the id, or you might have countless radio buttons, but you want to know which value will be sent to the server (the selected value of the group). So this answer doesn't really answers the questionCatalase
@Catalase Not sure what you mean, the OP says nothing about servers and asks (1) in his title how to check the value and (2) how to retrieve the value, both of which I've answered based on the code the OP provided.Chickpea
I see I didn't explain it very well: what you proposed will never ever work and doesn't even make sense. you absolutely cannot use getElementById in this situation. see this answer.Catalase
id arise the problem while getting the value,i have two id in same name it gets only 1st id value not second oneAppetitive
C
7

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>
Cutright answered 18/3, 2015 at 10:52 Comment(4)
This appears to have cross browser issues.Walcott
This no longer seems to work in Chrome either. I'm sure it did once. :(Cutright
you forgot .forms and .elements! so it should be document.forms.myForm.gender.valueUgly
Your answer seems so much easier to understand than the others thanks :).Gower
S
3

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

Shallot answered 5/3, 2012 at 4:30 Comment(0)
T
3

Another solution for ES5+

[...document.getElementsByName("gender")].find(input => input.checked).value;
Teasel answered 14/1, 2022 at 2:30 Comment(0)
I
1

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.

Ichthyosis answered 16/2, 2016 at 15:53 Comment(0)
E
-3

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

<input type="text" id="text" placeholder="Name">
Elvera answered 28/11, 2019 at 8:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.