1. 程式人生 > >帶搜尋功能的下拉選擇框select2

帶搜尋功能的下拉選擇框select2

<link href="http://select2.github.io/select2/select2-3.5.3/select2.css" rel="stylesheet">
<script src="http://select2.github.io/select2/select2-3.5.3/select2.js"></script>


<script type="text/javascript">  
    $(document).ready(function() {  
      var data = [{ id: 1, text: '中國' }, { id: 2, text: '美國' }, { id: 3, text: '日本' }, { id: 4, text: '加拿大' }];  
      $(".js-selecct-example").select2({  
        data: data,   //填充資料
        placeholder: "選擇國家", //填充預設值 
        allowClear:true, //是否允許清空
        multiple: true,  //是否支援多選
        ajax:{
            url:query_data.url, //輸入內容會由伺服器查詢並返回
            dataType: 'json',
            delay:251,
            data:function(params){
               return {
                   q:param, //輸入的內容
                   pagesize:20, //頁面大小
                   page:page //當前頁
               };
            },
            results: function (data, page) { 
                return { results: data.items };
            },
            cache: true
        }
      });  
      $(".js-select-example").select2('val','1')  
    });  
</script>  
  
<select class="js-select-example" name="country" multiple="multiple" id="country">  
</select>  




$('#country').val(); 

多選結果: ["2", "3"]

單選結果: 2

效果圖如下: