bootstrap-multiselect.js(下拉多选)如何动态更新select里的数据

在使用jQuery的bootstrap-multiselect插件(下拉多选)时可能会遇到一个问题

就是想要动态的去更新select里的数据


比如我们要使一个id=select的选择框实现多选

那么先用ajax获得新数据后清空select再一个个拼成option

[javascript]  view plain  copy
  1. $("#select").html("");  
  2. for (var i = 0; i < json.length; i++) {  
  3.     $("#select").append("<option value='" + json[i].code + "'>" + json[i].name + "</option>");  
  4. }  


这时再重新调用一次multiselect()或使用multiselect("refresh")可能并没有任何效果

正确的姿势应该是先使用destroy破坏multiselect之后再重新构建

[javascript]  view plain  copy
  1. $("#select").multiselect("destroy").multiselect({  
  2.     // 自定义参数,按自己需求定义  
  3.     nonSelectedText : '--请选择--',   
  4.     maxHeight : 350,   
  5.     includeSelectAllOption : true,   
  6.     numberDisplayed : 5  
  7. });  

最后代码如下

[javascript]  view plain  copy
  1. function refreshMultiSelect() {  
  2.     $.ajax({  
  3.         type : "POST",  
  4.         url : url,  
  5.         data : data,  
  6.         dataType : "json",  
  7.         success : function(json) {  
  8.             $("#select").html("");  
  9.             for (var i = 0; i < json.length; i++) {  
  10.                 $("#select").append("<option value='" + json[i].code + "'>" + json[i].name + "</option>");  
  11.             }  
  12.             $("#select").multiselect("destroy").multiselect({  
  13.                 // 自定义参数,按自己需求定义  
  14.                 nonSelectedText : '--请选择--',   
  15.                 maxHeight : 350,   
  16.                 includeSelectAllOption : true,   
  17.                 numberDisplayed : 5  
  18.             });  
  19.         }  
  20.     });  
  21. }  

猜你喜欢

转载自blog.csdn.net/qq_29347295/article/details/80348907
今日推荐