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

单选按钮点击Yes显示#current_school_details、点击No显示对应div的实现问题

问题原因

  • 原有两个函数各自仅控制单个div的显示状态,没有同步修改另一块div的状态,导致出现同时显示的问题
  • 两个函数都使用document.querySelector(".form-check-input"),该选择器只会匹配页面第一个符合条件的元素(即Yes对应的单选框),判断逻辑完全错误

修复方案

将两个逻辑合并为同一个统一处理函数,每次点击时同时修改两块div的显示状态,同时给两块div添加初始隐藏属性,避免页面刚加载时两块同时展示。

修改后的JS代码

function toggleSchoolDetails() {
  const yesChecked = document.getElementById("gridRadios1").checked;
  const yesDiv = document.getElementById("current_school_details");
  const noDiv = document.getElementById("current_school_details_two");

  yesDiv.style.display = yesChecked ? "block" : "none";
  noDiv.style.display = yesChecked ? "none" : "block";
}

修改后的HTML调整说明

  1. 两个单选框的onclick属性都替换为调用同一个处理函数
  2. 两块详情div添加初始隐藏样式
  3. 原有代码中多个input使用了重复的id="inputCity",同一页面id不能重复,下面的代码已统一修改为不同id避免后续出现其他问题

调整后的完整HTML代码:

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" >
<div>
  <legend class="col-form-label col-sm-12 pt-0">Are you currently a Twyford student?*</legend>
  <div class="col-sm-10">
    <div class="form-check">
      <input class="form-check-input" type="radio" name="gridRadios" id="gridRadios1" value="option1" onclick="toggleSchoolDetails();">
      <label class="form-check-label" for="gridRadios1">  Yes </label>
    </div>
    <div class="form-check">
      <input class="form-check-input" type="radio" name="gridRadios" id="gridRadios2" value="option2" onclick="toggleSchoolDetails();">
      <label class="form-check-label" for="gridRadios2"> No </label>
    </div>
  </div>
</div>
<div id="current_school_details" style="display: none;">
  <h2>Current School Details</h2>
  <select class="form-control">
    <option>--select--</option>
    <option>Twyford CofE High School</option>
    <option>Ealing Fields High School</option>
    <option>William Perkin CofE High School</option>
  </select>
</div>

<br>

<div id="current_school_details_two" style="display: none;">
  <h2>Current School Details</h2>
  <div class="form-row">
    <div class="form-group col-md-6">
      <label for="inputCity1">Current School*</label>
      <input type="text" class="form-control" id="inputCity1">
    </div>
    <div class="form-group col-md-6">
      <label for="inputCity2">School Address*</label>
      <input type="text" class="form-control" id="inputCity2">
    </div>
  </div>
  <div class="form-row">
    <div class="form-group col-md-6">
      <label for="inputCity3">Office Email*</label>
      <input type="text" class="form-control" id="inputCity3">
    </div>
    <div class="form-group col-md-6">
      <label for="inputCity4">Current Head of Year*</label>
      <input type="text" class="form-control" id="inputCity4">
    </div>
  </div>
</div>
</fieldset>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 00:06:04