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

Radio Button关联隐藏文本框异常:切换选项时无法隐藏文本框

问题解决:单选按钮切换时无法隐藏文本框的修正

核心错误分析

你的代码存在两个关键问题:

  1. 赋值运算符误用:条件判断里用了=(赋值)而非===(严格相等比较),这会导致条件永远为真,文本框一直处于显示状态。
  2. 缺少选中状态判断:仅判断单选按钮的value,但未检查该按钮是否被选中——单选按钮组中只有选中项的checked属性为true,即使value是"Other",未选中时也不应显示文本框。

修改后的函数代码

function showHideOther() {
    var radioButton = document.getElementById("master");
    var text = document.getElementById("dependent");
    // 同时判断按钮是否被选中、值是否为"Other"
    if (radioButton.checked && radioButton.value === "Other") {
        text.style.display = "block";
    } else {
        text.style.display = "none";
    }
}

额外注意事项

确保所有同组的单选按钮都绑定onchange事件调用该函数,这样切换任何选项时都会触发显示/隐藏逻辑:

<!-- 单选按钮组示例 -->
<input type="radio" name="optionGroup" id="master" value="Other" onchange="showHideOther()"> 其他
<input type="radio" name="optionGroup" value="Option1" onchange="showHideOther()"> 选项1
<input type="radio" name="optionGroup" value="Option2" onchange="showHideOther()"> 选项2

<!-- 隐藏的文本框 -->
<input type="text" id="dependent" style="display: none;" placeholder="请输入其他内容">

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 09:55:24