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.
This works in IE9 and above and all other browsers.
In Javascript we can get the values by using Id's "
getElementById()
" in the above code you posted has contain name not Id so you to modify like thisuse this rate_value according to your code
You can use
.find()
to select checked element:If you are using the
JQuery
, please use the bellow snippet for group of radio buttons.directly calling a radio button many times gives you the value of the FIRST button, not the CHECKED button. instead of looping thru radio buttons to see which one is checked, i prefer to call an
onclick
javascript function that sets a variable that can later be retrieved at will.which calls:
additional advantage being that i can treat data and/or react to the checking of a button (in this case, enabling SUBMIT button).
My take on this problem with pure javascript is to find the checked node, find its value and pop it out from the array.
Note that I'm using arrow functions. See this fiddle for a working example.