解決select2預設賦值問題
阿新 • • 發佈:2019-02-06
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:''})