使用Javascript拉取单选按钮值

时间:2016-02-20 20:26:06

标签: javascript html forms

我的网页上有一个表格如下:

<form id="numberForm">
<input type="radio" name="number" value="singular"> singular <br>
<input type="radio" name="number" value="plural"> plural <br>
</form>

如何在Javascript中提取当前所选单选按钮的值(没有提交操作)?

我喜欢的是以下内容:

var formInput = document.getElementById("numberForm");
var numberInputValue = formInput.SELECTEDBUTTON.value;

2 个答案:

答案 0 :(得分:2)

试试这个(在JS中使用querySelector):

&#13;
&#13;
function getSel() {
var formInput = document.getElementById("numberForm");
var rb=formInput.querySelector('[type="radio"]:checked'); //get selected radio button
document.getElementById('spVl').innerHTML = 'Selected value = '+rb.value;
}
&#13;
<form id="numberForm">
<input type="radio" name="number" value="singular"> singular <br>
<input type="radio" name="number" value="plural"> plural <br>
<input type="button" value="Get selected radio button value" onclick="getSel();" /><br>
<span id="spVl"></span>
</form>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

var form = document.getElementById('numberForm');
var radios = form.getElementsByTagName('input');

for(var i = 0; i < radios.length; ++i) {
  if(radios[i].checked) {
    console.log("Radio button '" + radios[i].value + "' is checked");
  }
}