简体   繁体   中英

How to check select list is multiple or not? Select2 JQuery, JavaScript

I have select list. It can be multiple or single select in case of action.

<select name="" id="cmb_employee"  class="js-example-basic-multiple" >
</select>

In cmb_employee on change/ I want to determinite select list is multiple or not. I tried this but it works for multiple not for single

 $("#cmb_employee").on('change', function () {
  var isMulti = document.getElementById('cmb_employee').multiple;
  if(isMulti){
     alert("is multi select");
    }
  else {
    alert("is not");
  }});

Note 1: I use Select2

 $('.js-example-basic-multiple').select2({ width: '100%', cushion: 54 });

Note 2: To change single to multiple

 $("#cmb_employee").select2({
                            multiple: true,
                            placeholder: "Seçin...",
                        });

Note 3: To change Multi to single select

 $("#cmb_employee").select2({
                                multiple: false,
                                placeholder: "Seçin...",
                            });

You can use select2 options to get the current status of multiple. $('#cmb_employee').data('select2').options.options.multiple

 $('#cmb_employee').select2({ placeholder: 'Select a month', multiple:true }); $("#single").click(function(){ $('#cmb_employee').select2({ placeholder: 'Select a month', multiple:false }); }) $("#multiple").click(function(){ $('#cmb_employee').select2({ placeholder: 'Select a month', multiple:true }); }) $("#check").click(function(){ console.log("is dropdown is multiple? "+$('#cmb_employee').data('select2').options.options.multiple); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link href="https://rawgit.com/select2/select2/master/dist/css/select2.min.css" rel="stylesheet"/> <script src="https://rawgit.com/select2/select2/master/dist/js/select2.js"></script> <select id="cmb_employee" style="width: 300px"> <option value="JAN">January</option> <option value="FEB">February</option> <option value="MAR">March</option> <option value="APR">April</option> <option value="MAY">May</option> <option value="JUN">June</option> <option value="JUL">July</option> <option value="AUG">August</option> <option value="SEP">September</option> <option value="OCT">October</option> <option value="NOV">November</option> <option value="DEC">December</option> </select> <button id="single"> Change to single </button> <button id="multiple"> Change to multiple </button> <button id="check"> Check dropdown is multiple or not </button> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM