1. 程式人生 > >解決select2預設賦值問題

解決select2預設賦值問題

1、資料來源於靜態資料

$(".test").select2({
            width: "100%",
            minimumResultsForSearch: -1,
            data:[{id:1,name:1},{id:2,name:2},
                  {id:3,name:3},{id:4,name:4},
                  {id:5,name:5}],
            formatSelection: function(item){
                return item
.name; }, formatResult: function(item){ return item.name; } }); 賦值 $(".test").val(1).trigger("change");

2、資料來源ajax請求

$(".test").select2({
            width: "100%",
            multiple: false,
            placeholder: "請選擇...",
            ajax: {
                url: "url"
, type: "post", dataType: "json", data:function(term, page){ return { start: (page - 1) * 10, length: 10 }; }, results:function(response, page, query)
{
} }, formatResult: this.proxy(function(item){ return item.name; }), formatSelection: this.proxy(function(item){ return item.name; }), id: this.proxy(function(item){ return item.value; }) }) //賦值 $(".test").select2("data",{id:'',name:''})