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

同页面问卷切换时动态检查单选按钮的实现方法咨询

解决方案:点击Next时检查当前问题的单选按钮

嘿,我完全懂你的场景!同一页面用div切换问卷问题,现在要在用户点「Next」时确保当前问题的单选按钮已经被选中对吧?咱们直接上实用的代码方案,一步步来:

核心思路

  1. 点击Next时,先定位当前正在显示的问题div
  2. 在这个div范围内查找所有单选按钮
  3. 检查是否有至少一个单选按钮被选中
  4. 如果没选中,阻止切换到下一题并给用户提示;如果选中了,执行原来的切换逻辑

具体实现代码

假设你的HTML结构大概是这样(可以根据实际结构调整类名):

<div class="questions-container">
  <div class="question-div">
    <p>问题1:你喜欢的颜色?</p>
    <input type="radio" name="color" value="red">红色
    <input type="radio" name="color" value="blue">蓝色
  </div>
  <div class="question-div" hidden>
    <p>问题2:你喜欢的动物?</p>
    <input type="radio" name="animal" value="cat">猫
    <input type="radio" name="animal" value="dog">狗
  </div>
</div>
<button id="back-btn">Back</button>
<button id="next-btn">Next</button>

对应的JavaScript逻辑:

// 获取Next按钮
const nextBtn = document.getElementById('next-btn');

// 绑定点击事件
nextBtn.addEventListener('click', function() {
  // 1. 找到当前显示的问题div(这里用hidden属性判断,如果你用display:none,替换成对应的选择器)
  const currentQuestion = document.querySelector('.question-div:not([hidden])');
  if (!currentQuestion) return; // 边界处理:没有显示的问题时直接返回

  // 2. 在当前问题里找所有单选按钮
  const radioButtons = currentQuestion.querySelectorAll('input[type="radio"]');
  
  // 3. 检查是否有单选按钮被选中
  const hasSelectedRadio = Array.from(radioButtons).some(radio => radio.checked);

  // 4. 如果当前问题有单选按钮但没选中,阻止切换
  if (radioButtons.length > 0 && !hasSelectedRadio) {
    // 这里可以换成更友好的提示,比如在问题下方显示错误文本
    alert('请选择一个选项后再继续哦!');
    return;
  }

  // 5. 执行原来的切换到下一题的逻辑(示例代码,可替换成你自己的切换逻辑)
  const nextQuestion = currentQuestion.nextElementSibling;
  if (nextQuestion && nextQuestion.classList.contains('question-div')) {
    currentQuestion.hidden = true;
    nextQuestion.hidden = false;
  }
});

一些优化建议

  • 如果你的隐藏/显示是用自定义类(比如.hide),把选择器改成document.querySelector('.question-div:not(.hide)')即可
  • 如果有些问题不需要强制选择(比如开放题),可以给需要检查的问题div加特殊类(比如.required-radio),然后在代码里加判断:if (currentQuestion.classList.contains('required-radio') && !hasSelectedRadio)
  • 尽量不用alert提示,建议在问题div下方添加一个错误提示元素(比如<p class="error-text" style="color:red;display:none;">请选择选项</p>),需要时显示它,用户体验更好

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:30:13