You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现JS生成的测验需勾选单选按钮才可进入下一题?

解决测验未选选项的校验问题

我来帮你搞定这个必须勾选至少一个radio才能进入下一题的需求!其实只需要在你的checkAnswer函数里加一小段校验逻辑就行,具体修改方案如下:

首先,在用户点击「Potvrdit odpoved」提交答案的分支里,先检查当前题目有没有radio被选中。如果没有,就提示用户,并且直接终止后续逻辑,不让用户进入下一题。

修改后的完整checkAnswer函数代码:

function checkAnswer() {
 // are we asking a question, or proceeding to next question?
 if (askingQuestion) {
  // 新增:校验是否有radio被选中
  var radios = document.getElementsByName("quiz" + currentQuestion);
  var hasSelected = false;
  for (var i = 0; i < radios.length; i++) {
   if (radios[i].checked) {
    hasSelected = true;
    break;
   }
  }
  if (!hasSelected) {
   alert("Prosím vyberte odpoveď!"); // 可自定义提示文本
   return; // 终止函数,阻止后续操作
  }

  submitBtn.textContent = "Dalsia otazka";
  askingQuestion = false;
  // determine which radio button they clicked
  var userpick, correctIndex;
  for (var i = 0; i < radios.length; i++) {
   if (radios[i].checked) {
    // if this radio button is checked
    userpick = radios[i].value;
   }
   // get index of correct answer
   if (radios[i].value == quiz[cQarr[currentQuestion]].correct) {
    correctIndex = i;
   }
  }
  // setup if they got it right, or wrong
  var labelStyle = document.getElementsByTagName("label") [correctIndex].style;
  labelStyle.fontWeight = "bold";
  if (userpick == quiz[cQarr[currentQuestion]].correct) {
   score++;
   labelStyle.color = "green";
  } else {
   labelStyle.color = "red";
  }
  scoreContainer.textContent = "Skore: " + score + " spravna odpoved " + quiz.length + " z moznych.";
 } else {
  // move to next question
  // setting up so user can ask a question
  askingQuestion = true;
  // change button text back to "Submit Answer"
  submitBtn.textContent = "Potvrdit odpoved";
  // if we're not on last question, increase question number
  if (currentQuestion < quiz.length - 1) {
   currentQuestion++;
   askQuestion();
  } else {
   showFinalResults();
  }
 }
}

关键修改说明:

  • 新增了遍历当前题目radio的逻辑,判断是否有选项被选中
  • 如果未选中任何选项,弹出提示并终止函数,这样用户就无法跳过当前题
  • 完全兼容你原有代码的逻辑,不需要改动其他部分

直接替换掉原来的checkAnswer函数,测试一下就能看到效果啦!

内容的提问来源于stack exchange,提问作者brankoo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 09:10:18