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

JavaScript人格测试表单验证需求:MOST与LEAST选同选项需弹窗提示

解决方案

核心思路

针对每个问题组,分别收集用户选中的「MOST」和「LEAST」对应的选项标识,若两者相同则触发提示并阻止表单提交。

步骤1:调整HTML结构

给每个问题容器添加统一类名(如question-group),同时给每个单选按钮加data-option属性标记所属选项:

<!-- 单个问题示例 -->
<div class="question-group">
  <h3>问题1:你更倾向于哪种社交方式?</h3>
  <div class="option">
    <p>和好友深度聊天</p>
    <label><input type="radio" name="q1-most" data-option="A"> MOST</label>
    <label><input type="radio" name="q1-least" data-option="A"> LEAST</label>
  </div>
  <div class="option">
    <p>参加多人聚会</p>
    <label><input type="radio" name="q1-most" data-option="B"> MOST</label>
    <label><input type="radio" name="q1-least" data-option="B"> LEAST</label>
  </div>
</div>

步骤2:编写验证逻辑

在表单提交事件中遍历每个问题组,检查是否存在同一选项同时被选为MOST和LEAST的情况:

document.querySelector('form').addEventListener('submit', function(e) {
  const questionGroups = document.querySelectorAll('.question-group');
  
  for (const group of questionGroups) {
    // 获取当前组选中的MOST和LEAST选项
    const selectedMost = group.querySelector('input[name$="-most"]:checked');
    const selectedLeast = group.querySelector('input[name$="-least"]:checked');
    
    // 验证逻辑:若两个选项都选中且标识相同
    if (selectedMost && selectedLeast && selectedMost.dataset.option === selectedLeast.dataset.option) {
      alert('当前问题中,不能同时将同一个选项选为MOST和LEAST!');
      e.preventDefault(); // 阻止表单提交
      return; // 终止后续检查
    }
  }
});

补充优化

如果需要明确提示是哪个问题出错,可以给问题组添加data-question属性,修改弹窗内容:

// 给问题组加属性:<div class="question-group" data-question="问题1">
alert(`${group.dataset.question}:不能同时将同一个选项选为MOST和LEAST!`);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 21:28:13