如何在Bootstrap 5多选下拉框的onchange事件中取消选择?
解决Bootstrap 5多选下拉框重复选中的取消操作
针对你遇到的两个多选下拉框互斥选中的需求,下面分两种常见实现场景给出解决方案,同时修正原代码中针对多选场景的逻辑缺陷:
场景1:原生Bootstrap 5多选下拉框(<select multiple>)
直接通过jQuery修改选项的选中状态,并同步下拉框状态:
// 给第一个下拉框绑定change事件 $('#ddlOne').on('change', function () { const $currentSelect = $(this); // 获取第二个下拉框已选中的所有值 const selectedInTwo = $('#ddlTwo').find('option:selected').map(function() { return this.value; }).get(); // 遍历当前下拉框的选中选项,检查是否重复 $currentSelect.find('option:selected').each(function() { const optionValue = this.value; if (selectedInTwo.includes(optionValue)) { alert(`选项 ${optionValue} 已在ddlTwo中被选中,取消当前选中...`); // 取消当前选项的选中状态 $(this).prop('selected', false); } }); // 触发change事件确保下拉框状态同步 $currentSelect.trigger('change'); }); // 给第二个下拉框绑定相同逻辑,实现双向互斥 $('#ddlTwo').on('change', function () { const $currentSelect = $(this); const selectedInOne = $('#ddlOne').find('option:selected').map(function() { return this.value; }).get(); $currentSelect.find('option:selected').each(function() { const optionValue = this.value; if (selectedInOne.includes(optionValue)) { alert(`选项 ${optionValue} 已在ddlOne中被选中,取消当前选中...`); $(this).prop('selected', false); } }); $currentSelect.trigger('change'); });
场景2:使用Bootstrap Select插件美化的下拉框
如果你的下拉框用了bootstrap-select插件(常见的Bootstrap下拉美化方案),需要调用插件提供的方法来修改状态并刷新UI:
// 第一个下拉框的事件监听(使用插件专属的changed.bs.select事件) $('#ddlOne').on('changed.bs.select', function (e, clickedIndex, isSelected) { const $currentSelect = $(this); const clickedOptionValue = $currentSelect.find('option').eq(clickedIndex).val(); // 获取第二个下拉框已选中的值(插件方法) const selectedInTwo = $('#ddlTwo').selectpicker('val') || []; // 仅当用户选中了重复选项时执行取消操作 if (isSelected && selectedInTwo.includes(clickedOptionValue)) { alert(`选项 ${clickedOptionValue} 已在ddlTwo中被选中,取消当前选中...`); // 调用插件方法取消选中 $currentSelect.selectpicker('deselect', clickedOptionValue); // 刷新插件UI状态 $currentSelect.selectpicker('refresh'); } }); // 第二个下拉框的双向互斥逻辑 $('#ddlTwo').on('changed.bs.select', function (e, clickedIndex, isSelected) { const $currentSelect = $(this); const clickedOptionValue = $currentSelect.find('option').eq(clickedIndex).val(); const selectedInOne = $('#ddlOne').selectpicker('val') || []; if (isSelected && selectedInOne.includes(clickedOptionValue)) { alert(`选项 ${clickedOptionValue} 已在ddlOne中被选中,取消当前选中...`); $currentSelect.selectpicker('deselect', clickedOptionValue); $currentSelect.selectpicker('refresh'); } });
关键说明
- 原生下拉框通过
prop('selected', false)直接修改选项的选中状态,再触发change事件确保状态同步。 - Bootstrap Select插件需要使用其提供的
deselect和refresh方法,因为插件会维护独立的DOM渲染层,直接修改option属性无法同步到UI。 - 两种方案都实现了双向互斥:任意一个下拉框选中的选项,另一个下拉框都无法选中。
内容的提问来源于stack exchange,提问作者John Butler
相关产品推荐
相关产品推荐

