JQuery implements dropdown multiple selection box

Time:2020-10-23

Recently, the company has an old project that needs to add some new functions. The old project is developed with jQuery. Now we need to make a drop-down multi-selection box. Many native UI plug-ins do not have a drop-down multi-selection box, or they need to add a Ctrl to make multiple selections. Here, the code below the drop-down multi-choice box made by UL Li is shown below:
HTML code:

<div class="divBox">
    <div class="duiMutiple">
      < div class = "divsel" > multi choice selection < / div >
      <ul id="usertype">
              < Li value = "1" > eating</li>
        < Li value = "2" > sleep</li>
        < Li value = "3" > playing with mobile phone</li>
      </ul>
    </div>
  </div>

Javascript code (remember to import jquery.js Document)

let setValList = [],setLabelList = [];
        //Select multiple selection
        $("#usertype").hide();
        $(".divSel").click(function() {
            $("#usertype").toggle();
        });
        $('#usertype li').click(function () {
            if(setValList.indexOf($(this).val()) === -1){
                setValList.push($(this).val());
                setLabelList.push($(this).text());
                $(this).addClass('optionSelStyle');
            }else {
                let index = setValList.indexOf($(this).val());
                setValList.splice(index,1);
                setLabelList.splice(index,1);
                $(this).removeClass('optionSelStyle');
            }
            console.log (setlabellist) // the data in the selected multiple check box
            $('.divSel').html(setLabelList.join(' '));
        })

CSS code:

.duiMutiple{
      width: 120px;
      height: 24px;
      position: relative;
      margin-top: 7px;
      display: block;
      .divSel{
        width: 93px;
        height: 24px;
        line-height: 24px;
        padding-left: 10px;
        cursor: pointer;
        background: #fff;
        border: 1px solid #95b7e7;
        position: absolute;
        top: 0;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      #usertype{
        width:120px;
        max-height:200px;
        border-radius:5px;
        background: #fff;
        border:1px solid #95b7e7;
        overflow: auto;
        margin-top: -20px;
        display: none;
        z-index: 99999!important;
        position: absolute;
        top: 48px;
        li{
          width: 90px;
          height: 30px;
          line-height: 30px;
          padding: 0 5px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          float: left;
        }
      }
      .optionSelStyle{
        background: #3188E1;
        color: #fff;
      }
    }