jQuery实现同name checkbox单选及选中值动态展示的方法
简洁实现代码
你需要的两个核心能力(同组checkbox单选控制、选中值实时展示到div)完全可以整合到同一个事件回调里完成,避免冗余的逻辑拆分。
基础实现(适配当前3个price复选框场景)
- 准备对应HTML结构,包含复选框组和值展示容器:
<!-- 同组价格复选框 --> <input type="checkbox" value="25,99" name="price"> <input type="checkbox" value="15,99" name="price"> <input type="checkbox" value="10,99" name="price"> <!-- 选中值展示div --> <div id="show-selected-value"></div>
- 绑定统一的change事件,同时完成两个核心逻辑:
$(function() { $('input[name="price"]').on('change', function() { // 取消其他同组复选框的选中状态,实现单选效果 $('input[name="price"]').not(this).prop('checked', false); // 读取当前选中状态,更新展示内容 const currentVal = $(this).prop('checked') ? $(this).val() : ''; $('#show-selected-value').text(currentVal); }); });
通用优化版本
如果后续页面还有其他同类型的“单选型复选框组”,可以把逻辑抽成通用能力,不用重复写绑定代码:
- 给每个复选框加
data-target属性,绑定对应的展示容器选择器
<!-- 价格组示例 --> <input type="checkbox" value="25,99" name="price" data-target="#show-price"> <input type="checkbox" value="15,99" name="price" data-target="#show-price"> <input type="checkbox" value="10,99" name="price" data-target="#show-price"> <div id="show-price"></div> <!-- 其他组示例,复用同一套逻辑 --> <input type="checkbox" value="basketball" name="sport" data-target="#show-sport"> <input type="checkbox" value="football" name="sport" data-target="#show-sport"> <div id="show-sport"></div>
- 写一次通用的事件绑定逻辑
$(function() { $('input[type="checkbox"][data-target]').on('change', function() { // 获取当前复选框所属的同组name const groupName = $(this).attr('name'); // 同组元素取消选中 $(`input[name="${groupName}"]`).not(this).prop('checked', false); // 更新对应容器的展示值 const target = $(this).data('target'); const currentVal = $(this).prop('checked') ? $(this).val() : ''; $(target).text(currentVal); }); });
逻辑说明:
- 不需要额外绑定按钮点击事件,只要复选框状态变化就会同步更新展示内容,交互更流畅
- 兼容“取消选中”操作:如果用户再次点击已选中的复选框取消选择,展示区会自动清空旧值,不会出现内容残留
- 没有重复的DOM查询操作,所有逻辑只触发一次事件回调,性能更好
内容的提问来源于stack exchange,提问作者newDev2000
相关产品推荐
相关产品推荐

