How to get value of selected radio button?

2018-12-31 09:54发布

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.

26条回答
君临天下
2楼-- · 2018-12-31 10:26

This works in IE9 and above and all other browsers.

document.querySelector('input[name="rate"]:checked').value;
查看更多
其实,你不懂
3楼-- · 2018-12-31 10:26

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 this

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

use this rate_value according to your code

查看更多
一个人的天荒地老
4楼-- · 2018-12-31 10:26

You can use .find() to select checked element:

var radio = Array.from(document.querySelectorAll('#rate input'))

var value = radio.length && radio.find(r => r.checked).value
查看更多
零度萤火
5楼-- · 2018-12-31 10:30

If you are using the JQuery, please use the bellow snippet for group of radio buttons.

var radioBtValue= $('input[type=radio][name=radiobt]:checked').val();
查看更多
呛了眼睛熬了心
6楼-- · 2018-12-31 10:31

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.

<input type="radio" onclick="handleClick(this)" name="reportContent" id="reportContent" value="/reportFleet.php" >

which calls:

var currentValue = 0;
function handleClick(myRadio) {
    currentValue = myRadio.value;
    document.getElementById("buttonSubmit").disabled = false; 
}

additional advantage being that i can treat data and/or react to the checking of a button (in this case, enabling SUBMIT button).

查看更多
一个人的天荒地老
7楼-- · 2018-12-31 10:32

My take on this problem with pure javascript is to find the checked node, find its value and pop it out from the array.

var Anodes = document.getElementsByName('A'),
    AValue = Array.from(Anodes)
       .filter(node => node.checked)
       .map(node => node.value)
       .pop();
console.log(AValue);

Note that I'm using arrow functions. See this fiddle for a working example.

查看更多
登录 后发表回答