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

单选按钮混合选项跳转失效及未选中校验需求求助

问题修复方案

原代码问题分析

  1. 循环逻辑错误:原代码遍历表单元素索引,仅当三个问题的同位置选项(全Yes或全No)被选中时才触发跳转,混合选项时没有匹配的索引条件,导致点击无响应。
  2. 缺少必填校验:未选中任何单选按钮时,没有弹出提示的校验逻辑。

修复后的代码

JavaScript 部分

<script type="text/javascript">
const x = "1.html";
const y = "2.html";

function redirectPage(form) {
    // 获取每个问题的选中值
    const answerq = form.querySelector('input[name="answerq"]:checked');
    const answerw = form.querySelector('input[name="answerw"]:checked');
    const answere = form.querySelector('input[name="answere"]:checked');

    // 必填校验:检查所有选项是否已选择
    if (!answerq || !answerw || !answere) {
        alert("请完成所有问题的选择!");
        return;
    }

    // 跳转逻辑:全Yes跳转x,其余情况(混合选项、全No)跳转y
    if (answerq.value === 'a' && answerw.value === 'a' && answere.value === 'a') {
        window.location = x;
    } else {
        window.location = y;
    }
}
</script>

HTML 部分

<form method="post" action="#">
    
*ARE YOU 18+ YEARS OLD?
<label><input type="radio" name="answerq" value="a"> Yes</label>
<label><input type="radio" name="answerq" value="b"> No</label>

*ARE YOU A U.S CITIZEN?
<label><input type="radio" name="answerw" value="a"> Yes</label>
<label><input type="radio" name="answerw" value="b"> No</label>

*ARE YOU MARRIED? 
<label><input type="radio" name="answere" value="a"> Yes</label>
<label><input type="radio" name="answere" value="b"> No</label>

<button type="button" class="btn btn-primary" onclick="redirectPage(this.form)">Submit!</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

</form>

修改说明

  • 移除错误的循环逻辑,改为直接通过querySelector获取每个单选组的选中项,避免索引匹配的限制。
  • 添加必填校验,若存在未选择的问题,弹出提示并终止后续操作。
  • 简化跳转判断:只要三个问题都已选择,全Yes跳转至1.html,其余所有情况(混合选项、全No)均跳转至2.html。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 16:43:12