我的网页上有一个表格如下:
<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;
答案 0 :(得分:2)
试试这个(在JS中使用querySelector
):
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;
答案 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");
}
}