Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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> 
like image 229
mkyong Avatar asked Mar 08 '12 13:03

mkyong


People also ask

How do I get radio selected value?

Get the value of selected radio button: querySelector() Remember you need to specify the name property of the radio button in HTML code. It is used as document. querySelector('input[name="JTP"]:checked') inside the <script> tab to check the selected radio button value from the group of radio buttons.

What is the value of a radio button?

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


1 Answers

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.

like image 160
Giorgos Tsakonas Avatar answered Oct 10 '22 02:10

Giorgos Tsakonas