bootstrap-multiselect.js如何动态更新select里的数据?

在使用jQuery的bootstrap-multiselect插件时可能会遇到一个问题

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

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

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

[javascript]view plaincopy

  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 plaincopy

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

最后代码如下

[javascript]view plaincopy

  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. }

版权声明:本文为博主原创文章,未经博主允许不得转载。 http://blog.csdn.net/qweasdqwe32/article/details/51722393