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

如何使用radio类型作为按钮且切换时不触发表单提交

实现单选按钮状态无提交切换的方案

你当前使用<button type="radio">的写法不会触发原生单选框的互斥逻辑,直接通过前端JavaScript绑定点击事件即可实现状态切换,不需要提交表单,具体实现方式如下:

方案1:原生JavaScript实现

给两个按钮绑定点击事件,点击时切换两个按钮的Bootstrap样式类和active状态即可:

// 先获取两个按钮元素
const rentBtn = document.getElementById('left');
const buyBtn = document.getElementById('right');
// 选中状态样式类
const activeClass = ['btn-secondary', 'active'];
// 未选中状态样式类
const inactiveClass = ['btn-light'];

// 给rent按钮绑定点击事件
rentBtn.addEventListener('click', function() {
  // 切换rent为选中状态
  rentBtn.classList.remove(...inactiveClass);
  rentBtn.classList.add(...activeClass);
  // 切换buy为未选中状态
  buyBtn.classList.remove(...activeClass);
  buyBtn.classList.add(...inactiveClass);
  // 如果需要存储当前选中值,可以自行维护变量,比如:
  // window.selectedType = 'rent';
});

// 给buy按钮绑定点击事件
buyBtn.addEventListener('click', function() {
  // 切换buy为选中状态
  buyBtn.classList.remove(...inactiveClass);
  buyBtn.classList.add(...activeClass);
  // 切换rent为未选中状态
  rentBtn.classList.remove(...activeClass);
  rentBtn.classList.add(...inactiveClass);
  // 存储选中值示例:
  // window.selectedType = 'buy';
});

方案2:jQuery实现(如果项目已引入jQuery)

代码更简洁:

$('#left, #right').on('click', function() {
  // 先把两个按钮都重置为未选中状态
  $('#left, #right').removeClass('btn-secondary active').addClass('btn-light');
  // 把当前点击的按钮设为选中状态
  $(this).removeClass('btn-light').addClass('btn-secondary active');
  // 获取当前选中值:const selectedVal = $(this).val();
});

补充优化建议

如果需要后续表单提交时能正确拿到选中值,建议把代码优化为隐藏原生<input type="radio">,按钮和input做关联,这样不需要额外维护选中值,原生表单就可以自动识别:

<div class="d-block">
  <div class="btn-group" role="group" aria-label="Basic example">
    <input type="radio" name="type" value="rent" id="rentRadio" class="d-none" checked>
    <label for="rentRadio" style="padding-right: 0 !important;" class="btn btn-lg btn-secondary pr-4 pl-0" id="left">{{ __('Rent') }}</label>
    <input type="radio" name="type" value="buy" id="buyRadio" class="d-none">
    <label for="buyRadio" style="padding-right: 0 !important;" class="btn btn-lg btn-light pr-4 pl-0" id="right">{{ __('Sale') }}</label>
  </div>
</div>

这种写法不需要额外写JS就可以自动实现互斥选中,点击label的时候会自动触发关联的radio选中,样式切换可以通过CSS的:checked伪类实现,也可以配合少量JS处理样式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 05:36:08