How to get value of selected radio button?

I want to get the selected value from a group of radio buttons.

Here's my HTML:

<div id="rates">
  <input type="radio" id="r1" name="rate" value="Fixed Rate"> Fixed Rate
  <input type="radio" id="r2" name="rate" value="Variable Rate"> Variable Rate
  <input type="radio" id="r3" name="rate" value="Multi Rate" checked="checked"> Multi Rate  
</div>

Here's my js:

var rates = document.getElementById('rates').value;
var rate_value;
if(rates =='Fixed Rate'){
    rate_value = document.getElementById('r1').value;
    
}else if(rates =='Variable Rate'){
    rate_value = document.getElementById('r2').value;
    
}else if(rates =='Multi Rate'){
    rate_value = document.getElementById('r3').value;
}  

document.getElementById('results').innerHTML = rate_value;

I keep getting undefined.


Solution 1:

This works in IE9 and above and all other browsers.

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

Solution 2:

var rates = document.getElementById('rates').value;

The rates element is a div, so it won't have a value. This is probably where the undefined is coming from.

The checked property will tell you whether the element is selected:

if (document.getElementById('r1').checked) {
  rate_value = document.getElementById('r1').value;
}

Or

$("input[type='radio'][name='rate']:checked").val();

Solution 3:

You can get the value by using the checked property.

var rates = document.getElementsByName('rate');
var rate_value;
for(var i = 0; i < rates.length; i++){
    if(rates[i].checked){
        rate_value = rates[i].value;
    }
}

Solution 4:

For you people living on the edge:

There is now something called a RadioNodeList and accessing it's value property will return the value of the currently checked input. This will remove the necessity of first filtering out the 'checked' input as we see in many of the posted answers.

Example Form

<form id="test">
<label><input type="radio" name="test" value="A"> A</label>
<label><input type="radio" name="test" value="B" checked> B</label>
<label><input type="radio" name="test" value="C"> C</label>
</form>

To retrieve the checked value, you could do something like this:

var form = document.getElementById("test");
alert(form.elements["test"].value);

The JSFiddle to prove it: http://jsfiddle.net/vjop5xtq/

Please note this was implemented in Firefox 33 (All other major browser seems to support it). Older browsers will require a polfyill for RadioNodeList for this to properly function

Solution 5:

The one worked for me is given below from api.jquery.com.

HTML

<input type="radio" name="option" value="o1">option1</input>
<input type="radio" name="option" value="o2">option2</input>

JavaScript

var selectedOption = $("input:radio[name=option]:checked").val()

The variable selectedOption will contain the value of the selected radio button (i.e) o1 or o2