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

如何根据选中的单选按钮禁用文本输入框?

实现单选按钮控制文本输入框的禁用状态

原代码的问题在于只在页面初始化时执行了一次状态判断,切换单选按钮后文本框状态不会自动更新。要解决这个问题,需要给单选按钮绑定change事件,实时监听选中状态变化,同步更新文本框的禁用状态。

下面是优化后的完整实现:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>单选按钮控制文本框禁用</title>
</head>
<body>
    <form>
        <label for="first">禁用文本框</label>
        <input type="radio" name="radios" id="first" checked>
        <br>
        <label for="second">启用文本框</label>
        <input type="radio" name="radios" id="second">
        <br>
        <input type="text" name="text" id="text" placeholder="测试输入框">
    </form>

    <script>
        // 获取页面元素
        const firstRadio = document.getElementById('first');
        const secondRadio = document.getElementById('second');
        const textInput = document.getElementById('text');

        // 统一处理文本框状态的函数
        function updateTextInputStatus() {
            // 第一个单选框选中则禁用文本框,否则启用
            textInput.disabled = firstRadio.checked;
        }

        // 页面加载时先执行一次,确保初始状态正确
        updateTextInputStatus();

        // 给两个单选按钮绑定状态变化事件
        firstRadio.addEventListener('change', updateTextInputStatus);
        secondRadio.addEventListener('change', updateTextInputStatus);
    </script>
</body>
</html>

关键说明:

  • 给单选按钮添加<label>标签,点击文字就能选中对应单选框,提升操作体验
  • 把状态更新逻辑封装成函数,避免重复代码,方便后续维护
  • 绑定change事件,单选按钮选中状态变化时立刻同步文本框状态
  • 页面初始化时调用状态更新函数,保证默认选中的单选按钮对应正确的文本框状态

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 20:12:15