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

在PHP Laravel中如何根据用户radio输入选择隐藏或显示表单字段

实现单选框控制字段显隐的方案

你可以通过监听单选框的change事件,配合if条件判断选中值实现需求,具体实现如下:

原生JavaScript实现(无需依赖第三方框架)

首先建议你给默认隐藏的spec字段外层容器加一个唯一id,方便获取元素、兼容性更好:

<!-- 修改后的spec字段外层div,新增id属性,内部原有代码不变 -->
<div id="specField" class="form-group row" style="display:none">
    <label for="spec" class="col-md-4 col-form-label text-md-right"> 
      {{ __('spec') }}
    </label>
    <div class="col-md-6">
        <input id="spec" type="text" class="form-control @error('spec') is-invalid @enderror" name="spec" value="{{ old('spec') }}" autocomplete="spec" autofocus>
      @error('spec')
          <span class="invalid-feedback" role="alert">
              <strong>{{ $message }}</strong>
          </span>
       @enderror
     </div>
  </div>

然后添加如下JS代码即可:

// 获取DOM元素
const radioList = document.querySelectorAll('input[name="fav_language"]');
const specField = document.getElementById('specField');

// 给每个单选框绑定选择事件
radioList.forEach(radio => {
  radio.addEventListener('change', function() {
    // if判断选中的单选框值
    if (this.value === 'JavaScript') {
      // 选中第二个选项时显示spec字段
      specField.style.display = 'flex';
      // 如果你用的是低版本Bootstrap,form-group是block布局,可以替换为:specField.style.display = 'block';
    } else {
      // 选中第一个选项时隐藏spec字段
      specField.style.display = 'none';
    }
  })
})

// 页面加载完成后初始化状态,兼容表单提交错误回显的场景
document.addEventListener('DOMContentLoaded', () => {
  const checkedRadio = document.querySelector('input[name="fav_language"]:checked');
  if (checkedRadio?.value === 'JavaScript') {
    specField.style.display = 'flex';
  }
})

可选:jQuery实现版本

如果你的项目已经引入了jQuery,可以使用更简洁的写法:

// 绑定change事件
$('input[name="fav_language"]').on('change', function() {
  if ($(this).val() === 'JavaScript') {
    $('#specField').show();
  } else {
    $('#specField').hide();
  }
})

// 初始化回显状态
$(function() {
  const checkedVal = $('input[name="fav_language"]:checked').val();
  if (checkedVal === 'JavaScript') {
    $('#specField').show();
  }
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 05:06:04