如何用HTML+JavaScript判断表单选项选中状态并开发测验
测验开发完整解决方案
一、修正并完善HTML结构
你的现有代码存在笔误:<be>需改为<br>。另外,单选框的value要设置成能区分正确/错误的值,方便后续JS判断。以下是包含2道题的完整HTML示例:
<form align="center" id="test"> <!-- 问题1 --> <div class="question"> Question 1: 以下哪个是HTML的根标签?<br> <input type="radio" name="radiogroup1" value="incorrect" id="q1-op1"> <label for="q1-op1">div</label><br> <input type="radio" name="radiogroup1" value="correct" id="q1-op2"> <label for="q1-op2">html</label><br> <input type="radio" name="radiogroup1" value="incorrect" id="q1-op3"> <label for="q1-op3">body</label><br> </div> <br> <!-- 问题2 --> <div class="question"> Question 2: JavaScript中声明变量的关键字不包括?<br> <input type="radio" name="radiogroup2" value="incorrect" id="q2-op1"> <label for="q2-op1">let</label><br> <input type="radio" name="radiogroup2" value="correct" id="q2-op2"> <label for="q2-op2">func</label><br> <input type="radio" name="radiogroup2" value="incorrect" id="q2-op3"> <label for="q2-op3">const</label><br> </div> <br> <button type="button" onclick="calculateScore()">提交测验</button> <p id="result"></p> </form>
这里用<label>绑定单选框,点击文字也能选中选项;每个问题用<div>包裹,结构更清晰。
二、实现JavaScript逻辑
添加以下代码,用来判断选中选项、计算正确答案数量并显示结果:
function calculateScore() { let score = 0; const form = document.getElementById('test'); // 所有问题的单选框组名称 const questionGroups = ['radiogroup1', 'radiogroup2']; questionGroups.forEach(groupName => { // 获取当前组中被选中的单选框 const selectedOption = form.querySelector(`input[name="${groupName}"]:checked`); // 判断是否选中且为正确选项 if (selectedOption && selectedOption.value === 'correct') { score++; } }); // 展示结果 const resultElement = document.getElementById('result'); resultElement.textContent = `你答对了 ${score} 题,共 ${questionGroups.length} 题`; }
三、关键要点说明
判断单选框选中状态:
用CSS选择器input[name="组名"]:checked可直接获取对应组的选中项,返回null则说明用户未选该题。添加选项的规范:
- 同一问题的单选框必须设置相同
name,确保单选互斥; - 每个单选框
id唯一,配合<label>提升交互体验; - 通过
value标记正确选项,简化JS判断逻辑。
- 同一问题的单选框必须设置相同
扩展更多题目:
复制<div class="question">块,修改name(如radiogroup3)、问题内容、选项及value,再将新name加入JS的questionGroups数组即可。
内容的提问来源于stack exchange,提问作者Dev
相关产品推荐
相关产品推荐

