如果选择了 radio 形式的选项,我正在尝试弄清楚如何检查和写入控制台。 即使选中了正确的选项,我也一直收到“未选中”的提示。 有任何想法吗? 我更喜欢不包含 JQuery 的解决方案,因为我研究的是 HTML 和 JavaScript。
谢谢!!
<body>
<form id="office">
<label id="ques1"> question 1</label><br/>
<div class="q1 wrong q1a1"><input type="radio" name="question1" value="q1a1" /> Answer1 <br/></div>
<div class="q1 wrong q1a2"><input type="radio" name="question1" value="q1a2" /> Answer2 <br/></div>
<div class="q1 wrong q1a3"><input type="radio" name="question1" value="q1a3" /> Answer3 <br/></div>
<div class="q1 right q1a4"><input type="radio" name="question1" value="q1a4" /> Answer4 <br/></div>
<br/><br/>
<input type="submit" id="submit" name="submitAnswers" value="Submit Your Answers" onclick="checkFunction()" />
</form>
<script type="text/javascript">
window.onload = function() {
document.getElementById('submit').onclick = function() {
if (document.querySelector('.q1 wrong q1a1').checked == true) {
console.log('checked');
} else {
console.log('not checked');
}
};
};
</script>
</body>
最佳答案
您正在检查 <div>
已选中,而不是单选按钮。
改变这一行:
if (document.querySelector('.q1 wrong q1a1').checked == true) {
类似于:
if (document.querySelector('input[type=radio][name=question1]').checked == true) {
关于javascript - 从单选按钮获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33919601/