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

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

我一直没有定义。


当前回答

多次直接调用单选按钮会给你FIRST按钮的值,而不是CHECKED按钮。我宁愿调用一个onclick javascript函数来设置一个变量,以便稍后可以随意检索,而不是循环遍历单选按钮来查看哪个按钮被选中。

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

电话:

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

额外的好处是我可以处理数据和/或对按钮的检查做出反应(在这种情况下,启用SUBMIT按钮)。

其他回答

这适用于IE9及以上版本和所有其他浏览器。

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

多次直接调用单选按钮会给你FIRST按钮的值,而不是CHECKED按钮。我宁愿调用一个onclick javascript函数来设置一个变量,以便稍后可以随意检索,而不是循环遍历单选按钮来查看哪个按钮被选中。

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

电话:

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

额外的好处是我可以处理数据和/或对按钮的检查做出反应(在这种情况下,启用SUBMIT按钮)。

我使用了jQuery。点击function获得所需的输出:

$('input[name=rate]').click(function(){
  console.log('Hey you clicked this: ' + this.value);

  if(this.value == 'Fixed Rate'){
    rate_value = $('#r1').value;
  } else if(this.value =='Variable Rate'){
   rate_value = $('#r2').value;
  } else if(this.value =='Multi Rate'){
   rate_value = $('#r3').value;
  }  

  $('#results').innerHTML = rate_value;
});

希望能有所帮助。

对我有用的是下面api.jquery.com上给出的。

HTML

<input type="radio" name="option" value="o1">option1</input>
<input type="radio" name="option" value="o2">option2</input>

JavaScript

var selectedOption = $("input:radio[name=option]:checked").val()

变量selectedOption将包含所选单选按钮的值(即o1或o2)

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

var radioBtValue= $('input[type=radio][name=radiobt]:checked').val();