天天看點

下拉多選checkbox

  • 本文原創,轉載請注明出處
      • CSS代碼
      • HTML代碼
      • JS代碼
      • 全部代碼

今天根據要求讓實作下拉清單加入多選按鈕,之前寫過百度搜尋效果,但是感覺不太适用。然後大概想了一下就動手開始試着去寫,實作效果如下圖:

下拉多選checkbox

(注:選中下拉多選框之後點選輸入框及下拉以外的地方隐藏下拉。依賴JQuery,為了寫的友善些。)

CSS代碼

定義一些樣式:

<style>
      ul li{
        list-style: none;
       }
      .hide{display: none}
      .width150{
        width: px;
    }
      .width150 input[type="text"]{
          width: %;  
          height: px;  
          border: px solid #ccc;  
          border-radius: px;  
          padding-left: px;
      }
       .width150 ul{ 
           width: %; 
           padding:    px; 
           margin: ; 
           border: px solid #ccc; 
       }
       .width150 li{ 
           padding: px; 
       }
       .width150 li+li{ 
           border-top: px solid #ccc; 
       }
   </style>
           

HTML代碼

定義輸入框和顯示下拉的ul:

<form id="form">    
    <div class="width150">
        可多選年份:<input type="text" id="yearInput" placeholder="請選擇年份" readonly>
        <ul id="yearId" class="hide">
        </ul>
    </div>
</form>
           

JS代碼

定義json資料、擷取checkbox選中内容等:

<script>
    (function(){
        var str = '';
        var arr = {
             : {name:'2015',id:},
             : {name:'2016',id:},
             : {name:'2017',id:}
        };
        for (let x in arr){
            console.info(x);
            str += `<li><label><input type="checkbox" value="${arr[x].id}" data-name="${arr[x].name}">${arr[x].name}</label></li>`;
        }
        $('#yearId').html(str);
    })();

    $("#yearInput").click(function(){
        $(this).attr('placeholder','');
        var name = '';
        $('#yearId input').each(function () {//循環周遊checkbox
            var  check=$(this).is(':checked');//判斷是否選中
            if(check){
                name += $(this).attr('data-name')+',';
                $(this).attr('name',"yearId");
            }else {
                $(this).attr('name',"");
            }
        });
        $("#yearInput").val(name.slice(,-));//去除最後的逗号
    });

    $("#yearId").mouseover(function() {
        if (!$("#yearId").hasClass('hover')){//類hover在下面用來驗證是否需要隐藏下拉,沒有其他用途。
            $("#yearId").addClass('hover');
        }
    }).mouseout(function(){
        $("#yearId").removeClass('hover');
    });

    $(document).on('click',function() {
        if (!$("#yearInput").is(":focus") && !$("#yearId").hasClass('hover')) {//如果沒有選中輸入框且下拉不在hover狀态。

            var name = '';
            $('#yearId input').each(function () {//周遊checkbox
                var check = $(this).is(':checked');//判斷是否選中
                if (check) {
                    name += $(this).attr('data-name') + ',';
                    $(this).attr('name', "yearId");
                } else {
                    $(this).attr('name', "");
                }
            });
            $("#yearInput").val(name.slice(, -));//去除最後的逗号
            $("#yearId").addClass('hide');
        } else {
            $("#yearId").removeClass('hide');
        }
    });
</script>
           

上面代碼input輸入框顯示的是資料的name,要是需要把id傳到後端,就把checkbox的value傳出去,可以用$(“#form”).serialize();擷取選中的checkbox。

要想下拉有滾動條,設定一下 ul樣式:

.width150 ul{
     width: %;
     padding:    px;
     margin: ;
     border: px solid #ccc;
     height: px;
     overflow-y: scroll;
}
           

全部代碼

<!doctype html>
<html hljs-string">"en">
<head>
    <meta charset="UTF-8">
    <title>下拉多選</title>
    <script src="http://libs.baidu.com/jquery/1.11.1/jquery.min.js"></script>
    <style>
        ul li{
            list-style: none;
        }
        .hide{display: none}
        .width150{
            width: px;
        }
        .width150 input[type="text"]{
            width: %;
            height: px;
            border: px solid #ccc;
            border-radius: px;
            padding-left: px;
        }
        .width150 ul{
            width: %;
            padding:    px;
            margin: ;
            border: px solid #ccc;
        }
        .width150 li{
            padding: px;
        }
        .width150 li+li{
            border-top: px solid #ccc;
        }
    </style>
</head>
<body>
<form id="form">
    <div class="width150">
        可多選年份:<input type="text" id="yearInput" placeholder="請選擇年份" readonly>
        <ul id="yearId" class="hide">
        </ul>
    </div>
</form>
<script>
    (function(){
        var str = '';
        var arr = {
             : {name:'2015',id:},
             : {name:'2016',id:},
             : {name:'2017',id:}
        };
        for (let x in arr){
            console.info(x);
            str += `<li><label><input type="checkbox" value="${arr[x].id}" data-name="${arr[x].name}">${arr[x].name}</label></li>`;
        }
        $('#yearId').html(str);
    })();

    $("#yearInput").click(function(){
        $(this).attr('placeholder','');
        var name = '';
        $('#yearId input').each(function () {//循環周遊checkbox
            var  check=$(this).is(':checked');//判斷是否選中
            if(check){
                name += $(this).attr('data-name')+',';
                $(this).attr('name',"yearId");
            }else {
                $(this).attr('name',"");
            }
        });
        $("#yearInput").val(name.slice(,-));//去除最後的逗号
    });

    $("#yearId").mouseover(function() {
        if (!$("#yearId").hasClass('hover')){//類hover在下面用來驗證是否需要隐藏下拉,沒有其他用途。
            $("#yearId").addClass('hover');
        }
    }).mouseout(function(){
        $("#yearId").removeClass('hover');
    });

    $(document).on('click',function() {
        if (!$("#yearInput").is(":focus") && !$("#yearId").hasClass('hover')) {//如果沒有選中輸入框且下拉不在hover狀态。
            var name = '';
            $('#yearId input').each(function () {//周遊checkbox
                var check = $(this).is(':checked');//判斷是否選中
                if (check) {
                    name += $(this).attr('data-name') + ',';
                    $(this).attr('name', "yearId");
                } else {
                    $(this).attr('name', "");
                }
            });
            $("#yearInput").val(name.slice(, -));//去除最後的逗号
            $("#yearId").addClass('hide');
        } else {
            $("#yearId").removeClass('hide');
        }
    });
</script>
</body>
</html>