You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何使用JavaScript实现选中radio button后隐藏关联的radio button及对应label

解决预订表单中根据开始时间动态隐藏超时时长的问题

嗨,你的这个预订表单需求很实用啊,就是要避免用户选了开始时间后,选的时长导致结束时间跨到第二天(超过24点)对吧?我看了你的代码,有几个小细节没处理好,咱们来一步步修正它:

原代码里的几个问题

  • 变量作用域漏了声明:循环里的ix没加let/var,会变成全局变量,容易引发奇怪的bug
  • 时间计算逻辑错了:你把开始时间转成12小时制的PM值来计算,但判断结束时间是否超午夜,应该用原始的24小时制数值才对
  • DOM操作有误durLabel是元素集合,不能直接用durLabel.style.display;还有循环里的durSelect[a]a根本没定义,应该是durSelect[x];获取label的for属性也有写法问题

修正后的完整代码

JavaScript部分

// 获取DOM元素,用const/let避免全局变量污染
const dateRow = document.getElementById('dateCollapse');
const datePick = document.getElementById('dp1');
const showDate = document.getElementById('dateSelect');
const timeCell = document.getElementsByClassName('time-cell');
const tiSelect = document.getElementsByName('startTime');
const durSelect = document.getElementsByName('duration');
const durLabels = document.getElementsByClassName('durationLabel'); // 改名更清晰

// 给所有开始时间单选按钮绑定事件
tiSelect.forEach(radio => {
  radio.addEventListener('change', updateAvailableDurations);
});

function updateAvailableDurations() {
  // 找到当前选中的开始时间
  const selectedStartTime = Array.from(tiSelect).find(radio => radio.checked);
  if (!selectedStartTime) return; // 没选中的话直接返回
  
  // 获取开始时间的24小时制数值
  const startHour = parseInt(selectedStartTime.value);
  
  // 更新页面上显示的12小时制时间(保留你原来的PM格式)
  let timeDisplay = startHour % 12;
  timeDisplay = timeDisplay === 0 ? 12 : timeDisplay;
  document.getElementById("timeSelect").innerHTML = `${timeDisplay} PM`;

  // 遍历所有时长选项,判断是否需要隐藏
  Array.from(durSelect).forEach((durRadio, index) => {
    const duration = parseInt(durRadio.value);
    const endHour = startHour + duration;
    
    // 判断结束时间是否超过24点(如果允许到24点,就改成endHour > 24)
    const isOverMidnight = endHour > 24;
    
    // 找到对应的label元素(按索引匹配,确保HTML里顺序一致)
    const correspondingLabel = durLabels[index];
    
    if (isOverMidnight) {
      // 隐藏单选按钮和对应的label
      durRadio.style.display = 'none';
      correspondingLabel.style.display = 'none';
      // 如果这个时长之前是选中状态,取消选中
      if (durRadio.checked) {
        durRadio.checked = false;
      }
    } else {
      // 恢复显示
      durRadio.style.display = '';
      correspondingLabel.style.display = '';
    }
  });
}

// 页面加载时自动执行一次,确保初始状态正确
window.addEventListener('load', updateAvailableDurations);

HTML部分(只需小调整)

你的HTML结构没问题,只需要去掉时长单选按钮上的onchange="displayEnd()"就行,因为我们已经通过JS监听了开始时间的变化,自动触发时长更新:

<div class="col-md-12">
  <div class="row d-flex">
    <div class="col mx-3 my-1 py-1 card-header bg-blk raj-wt fs-4 text-center"> Duration </div>
  </div>
  <div class="row d-flex text-center mx-0">
    <label for="1hr" class="col-4 mx-0 d-inline-block px-1 dur-cell durationLabel">
      <span class="raj-wt text-center fs-6 py-1">
        <input id="1hr" value="1" type="radio" name="duration" > 1HR
      </span>
    </label>
    <label for="2hrs" class="col-4 d-inline-block mx-0 px-1 dur-cell durationLabel">
      <span class="raj-wt text-center fs-6 py-1">
        <input id="2hrs" value="2" type="radio" name="duration" > 2HRS
      </span>
    </label>
    <label for="3hrs" class="col-4 d-inline-block mx-0 px-1 dur-cell durationLabel">
      <span class="raj-wt text-center fs-6 py-1">
        <input id="3hrs" value="3" type="radio" name="duration" > 3HRS
      </span>
    </label>
  </div>
</div>

关键逻辑说明

  1. 事件绑定更合理:不再依赖HTML内联事件,用JS统一绑定开始时间的change事件,代码更整洁解耦
  2. 时间计算准确:直接用开始时间的24小时数值计算结束时间,避免12小时制转换带来的错误
  3. DOM操作更严谨:通过索引匹配时长单选按钮和对应的label,确保每个选项都能正确显示/隐藏;同时处理了隐藏选项被选中的情况,避免提交无效数据
  4. 初始状态处理:页面加载时自动执行一次函数,确保如果有默认选中的开始时间,时长选项会立刻调整到正确状态

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

火山引擎 最新活动