I looked everywhere and tried everything 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.
The rates element is a
div
, so it won't have a value. This is probably where theundefined
is coming from.The
checked
property will tell you whether the element is selected: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
To retrieve the checked value, you could do something like this:
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 functionIf you are using jQuery:
$('input[name="rate"]:checked').val();
check value by ID:
HTML CODE:
<input type="radio" name="rdoName" value="YES"/> <input type="radio" name="rdoName" value="NO"/>
JQUERY CODE:
You will get
You can get the value by using the
checked
property.