【发布时间】:2016-01-23 22:38:57
【问题描述】:
我正在使用单选按钮在表单上收集简单的是/否输入。
表单内的 HTML 代码:
<label for="sociable">Yes</label>
<input type="radio" name="sociable" id="sociable" value="1">
<label for="sociable">No</label>
<input type="radio" name="sociable" id="sociable" value="2" checked>
我正在使用 JavaScript 通过 ID 确定值是什么:
var userSociable = document.getElementsByName("sociable")
if (userSociable[0].checked) {
userInput.push("1");
} else if (userSociable[1].checked) {
userInput.push("2");
}
当我验证代码时,我得到一个我理解的重复 ID 错误,以及为什么会这样,我的问题是,如何在不更改 JavaScript 的情况下解决这个问题?对同一输入使用两个不同的 ID 对我来说似乎不合逻辑。
【问题讨论】:
-
Duplicate Id 是无效标记,更改 HTML 以使 ID 唯一,然后使用
userInput.push(document.querySelector('[name="sociable"]:checked').value); -
不能在一个文档中定义多个同名id
标签: javascript html radio-button duplicates