无法获取单选按钮的值

时间:2019-05-17 21:21:40

标签: javascript html input radio-button

我无法获得第二和第三个单选按钮的值。 选择此代码后,我的代码只会给我第一个单选按钮值。

这是我的单选按钮,也是我想用来存储单选按钮值的功能。

<input type="radio" id="choiced" name="Q0_choice" value="one">
<input type="radio" id="choiced" name="Q0_choice" value="2">
<input type="radio" id="choiced" name="Q0_choice" value="iii">



next.onclick = function () {
    if (document.getElementById('choiced').checked) {
        ans = document.getElementById('choiced').value;
    }
}

3 个答案:

答案 0 :(得分:0)

这是因为ID值必须是唯一的-因此它将抓取ID为choiced的页面上的第一个元素。您需要为每个ID赋予唯一的ID,并且可以使用name属性对单选按钮进行分组。参见https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/radio

答案 1 :(得分:0)

尝试

document.querySelector('#choiced:checked')

此查询返回选中的单选按钮。

答案 2 :(得分:0)

对于这些输入,您不应使用相同的ID:

<input type="radio" id="choiced" name="Q0_choice" value="one">
<input type="radio" id="choiced2" name="Q0_choice" value="2">
<input type="radio" id="choiced3" name="Q0_choice" value="iii">

然后要获取所选内容,您必须通过name属性来获取它们。您可以循环检查选择了哪一个。

next.onclick = function () {
    const radios = document.getElementsByName('Q0_choice');
    radios.forEach((radio) => {
        if (radio.checked){
          console.log(radio.value);
        }
    })
}
相关问题