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

如何在点击单选框选项后执行JavaScript函数?

原生JavaScript实现单选框点击显示文本框

完整代码实现

HTML

<!-- 单选框组 -->
<input type="radio" id="yes" name="option">
<label for="yes">Yes</label><br><br>
<input type="radio" id="no" name="option" checked>
<label for="no">No</label><br><br>

<!-- 需要显示/隐藏的区域 -->
<div id="diet-section" style="display: none;">
  <label for="edietq">If yes, explain your dietary restrictions</label><br> 
  <input type="text" id="edietq" name="edietq"><br><br>
</div>

JavaScript

function handleOptionChange() {
  const dietSection = document.getElementById('diet-section');
  // 判断Yes单选框是否被选中
  if (document.getElementById('yes').checked) {
    dietSection.style.display = 'block';
  } else {
    dietSection.style.display = 'none';
  }
}

function init() {
  // 给所有同组单选框绑定change事件
  const radioOptions = document.querySelectorAll('input[name="option"]');
  radioOptions.forEach(radio => {
    radio.addEventListener('change', handleOptionChange);
  });
}

window.onload = init;

关键说明

  • 监听change事件而非click:点击单选框或其关联的label都会触发radio的change事件,覆盖所有交互场景,比单独监听click更可靠
  • 初始隐藏目标区域:通过style="display: none;"让饮食说明区域默认隐藏,避免页面加载时的视觉闪烁
  • 批量绑定事件:通过querySelectorAll选中所有同组单选框,一次性绑定事件,同时处理Yes和No的切换逻辑
  • 用checked属性判断状态:直接通过radio元素的checked属性判断是否被选中,逻辑清晰直观

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 11:45:45