如何用Bootstrap、HTML及JavaScript实现多选复选框下拉菜单并展示选中项
实现方案
完全可以用Bootstrap + 原生JS实现你要的多选下拉效果,前提是页面已经引入了Bootstrap对应的CSS、JS以及jQuery依赖,只需两步修改即可:
1. 修正HTML结构
给承载选项的ul标签添加Bootstrap下拉菜单必需的dropdown-menu类,保证下拉交互正常生效,修改后的完整HTML代码如下:
<div>Country</div> <div class="row" name="country_checkbox" id="id_row"> <div class="dropdown"> <a aria-expanded="false" aria-haspopup="true" role="button" data-toggle="dropdown" class="dropdown-toggle" href="#"> <span id="selected">Choose option</span><span class="caret"></span> </a> <!-- 新增dropdown-menu类 --> <ul id="id_country" class="dropdown-menu"> <li> <label for="id_country_0"> <input type="checkbox" name="country" value="US" placeholder="Select Country" id="id_country_0" onclick="filter_type();"> US </label> </li> <li> <label for="id_country_1"> <input type="checkbox" name="country" value="India" placeholder="Select Country" id="id_country_1" onclick="filter_type();"> India </label> </li> <li> <label for="id_country_2"> <input type="checkbox" name="country" value="Japan" placeholder="Select Country" id="id_country_2" onclick="filter_type();"> Japan </label> </li> <li> <label for="id_country_3"> <input type="checkbox" name="country" value="UK" placeholder="Select Country" id="id_country_3" onclick="filter_type();"> UK </label> </li> </ul> </div> </div>
2. 添加JS逻辑
你原来代码里调用的filter_type函数写下面这段就行,逻辑是每次点击复选框时,收集所有已选中的国家名称,替换按钮上的显示文本:
function filter_type() { // 获取所有选中的国家复选框 const checkedBoxes = document.querySelectorAll('input[name="country"]:checked'); // 提取选中的国家名称 const selectedCountries = Array.from(checkedBoxes).map(item => item.value); // 替换按钮显示文本 const selectedTextEl = document.getElementById('selected'); if (selectedCountries.length === 0) { selectedTextEl.textContent = 'Choose option'; } else { selectedTextEl.textContent = selectedCountries.join('、'); } // 阻止点击复选框时关闭下拉菜单,方便连续多选 event.stopPropagation(); }
效果说明
勾选任意国家后,下拉按钮的文本会实时替换为你选中的所有国家名称,没有选中时恢复默认提示;点击复选框时不会自动收起下拉菜单,可以连续选择多个选项。
内容的提问来源于stack exchange,提问作者imran_44
相关产品推荐
相关产品推荐

