我想从一组单选按钮中获得选定的值。

这是我的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>

这是我的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;

我一直没有定义。


当前回答

如果你正在使用jQuery:

$('input[name=“rate”]:checked').val();

其他回答

对前面建议功能的改进:

function getRadioValue(groupName) {
    var _result;
    try {
        var o_radio_group = document.getElementsByName(groupName);
        for (var a = 0; a < o_radio_group.length; a++) {
            if (o_radio_group[a].checked) {
                _result = o_radio_group[a].value;
                break;
            }
        }
    } catch (e) { }
    return _result;
}

你可以使用.find()来选择选中的元素:

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

var value = radio.length && radio.find(r => r.checked).value

var rates=document.getElementsByName("rate"); for (i = 0; i < rates.length; i++) { if (rates[i].checked) { console.log(rates[i].value); rate=rates[i].value; document.getElementById("rate").innerHTML = rate; alert(rate); } } <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> </br> <div id='rate'> </div>

如果你正在使用JQuery,请使用下面的单选按钮组片段。

var radioBtValue= $('input[type=radio][name=radiobt]:checked').val();
<form id="rates">
  <input type="radio" name="rate" value="Fixed Rate"> Fixed
  <input type="radio" name="rate" value="Variable Rate"> Variable
  <input type="radio" name="rate" value="Multi Rate" checked> Multi
</form>

然后……

var rate_value = rates.rate.value;