動态修改select2下拉清單内容
select2官方文檔位址:http://select2.github.io/select2/#documentation
1、html代碼及select2初始化
<div class="form-group">
<label for="form_sl_class" class="control-label">******</label>
<select class="form-control" id="form_sl_class" name="form_sl_class">
<option></option>
</select>
</div>
$("#form_sl_class").select2({
placeholder: "請選擇******",
data: [
{ id: 1, text: "***" },
{ id: 2, text: "***" },
{ id: 3, text: "***" }
],
allowclear: true
});
2、動态修改select2下拉清單内容
function editSelect2(classdata){
var instance = $("#form_sl_class").data('select2');
if (instance) {
//清空銷毀已有select2
$("#form_sl_class").select2('destroy').empty();
}
// 注:使用setTimeout方法間隔一段時間後執行select2初始化,否則可能初始化失敗
setTimeout(function () {
$("#form_sl_class").select2({
placeholder: "請選擇******",
data: classdata, // 重新設定新資料
allowClear: true
});
}, 100)
}