使用bootstrap 的下拉選單實現select的下拉複選框多選
阿新 • • 發佈:2018-12-31
CSS程式碼:
/*多選下拉框樣式(根據自己的樣式調整)*/ .dropdown_item{width: 100%} .dropdown_item>li:HOVER{background-color: #eee;cursor: pointer;} .dropdown_item>li {display: block;padding: 3px 10px;clear: both;font-weight: normal;line-height: 1.428571429;color: #333;white-space: nowrap;} .dropdown_item>li>.check_box{width: 18px;height: 18px;vertical-align: middle;margin: 0px;} .dropdown_item>li>span{vertical-align: middle;} .select_multiple .caret{border-top: 4px solid!important;border-bottom: 0;}
HTML程式碼:
<div class="dropup" style="position: relative;"> <button class="btn btn-default dropdown-toggle form-control select_multiple" style="width: 100%;margin-left: 0px;" type="button" id="dropdownMenu21" data-toggle="dropdown"> <span class="select_text" data-is-select="false">Dro pup</span> <span class="caret"></span> </button> <ul class="dropdown-menu dropdown_item" style="bottom: auto;"> <li><input type="checkbox" class="check_box" value="aa" /> <span>Action</span></li> <li><input type="checkbox" class="check_box" value="bb"/> <span>Another action</span></li> <li><input type="checkbox" class="check_box" value="cc"/> <span>Something else here</span></li> <li><input type="checkbox" class="check_box" value="dd"/> <span>Separated link</span></li> </ul><!-- 為了方便演示,type設定text了,實際中可以設定成hidden --> <input type="text" name="" class="select_val"/> </div>
JS程式碼:
//多選下拉框實現 $(document).on("click",".check_box",function(event){ event.stopPropagation();//阻止事件冒泡,防止觸發li的點選事件 //勾選的項 var $selectTextDom=$(this).parent().parent("ul").siblings("button").children(".select_text"); //勾選項的值 var $selectValDom=$(this).parent().parent("ul").siblings(".select_val"); //是否有選擇項了 var isSelected=$selectTextDom[0].getAttribute("data-is-select"); var selectText="";//文字值,用於顯示 var selectVal=$selectValDom.val();//實際值,會提交到後臺的 var selected_text=$(this).siblings("span").text();//當次勾選的文字值 var selected_val=$(this).val();//當次勾選的實際值 //判斷是否選擇過 if(isSelected=="true"){ selectText=$selectTextDom.text(); } if(selectText!=""){ if(selectText.indexOf(selected_text)>=0){//判斷是否已經勾選過 selectText=selectText.replace(selected_text,"").replace(",,",",");//替換掉 selectVal=selectVal.replace(selected_val,"").replace(",,",",");//替換掉 //判斷最後一個字元是否是逗號 if(selectText.charAt(selectText.length - 1)==","){ //去除末尾逗號 selectText=selectText.substring(0,selectText.length - 1); selectVal=selectVal.substring(0,selectVal.length - 1); } }else{ selectText+=","+selected_text; selectVal+=","+selected_val; } }else{ selectText=selected_text; selectVal=selected_val; } $selectTextDom.text(selectText); $selectValDom.val(selectVal); if(selectText==""){ $selectTextDom.text("請選擇"); $selectTextDom[0].setAttribute("data-is-select","false"); }else{ $selectTextDom[0].setAttribute("data-is-select","true"); } })
實現效果: