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

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

我一直没有定义。


当前回答

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>

其他回答

https://codepen.io/anon/pen/YQxbZJ

HTML

<div id="rates">
<input type="radio" id="x1" name="rate" value="Fixed Rate"> Fixed Rate
<input type="radio" id="x2" name="rate" value="Variable Rate" 
checked="checked"> Variable Rate
<input type="radio" id="x3" name="rate" value="Multi Rate" > Multi Rate
</div>

<button id="rdio"> Check Radio </button>
<div id="check">

</div>

JS的

var x ,y;
var x = document.getElementById("check");
function boom()
{
if (document.getElementById("x1").checked)
  y = document.getElementById("x1").value;

else if(document.getElementById("x2").checked)
  y = document.getElementById("x2").value;

else if (document.getElementById("x3").checked)
  y = document.getElementById("x3").value;
else
  y = "kuch nhi;"
x.innerHTML = y;
}

var z = document.getElementById('rdio');
z.addEventListener("click", boom);`

如果你正在使用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;
}

您可以使用checked属性来获取该值。

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;
    }
}

如果你正在使用javascript而不是jQuery,你可以使用这个命令:

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