bootstrap-select用法详解
首先需要引入
<!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.10.0/css/bootstrap-select.min.css"> <!-- Latest compiled and minified JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.10.0/js/bootstrap-select.min.js"></script> <!-- (Optional) Latest compiled and minified JavaScript translation files --> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.10.0/js/i18n/defaults-*.min.js"></script>
用法
<select id="usertype" style="width: 257px;" name="usertype" class="selectpicker show-tick" title="请选择" multiple data-live-search="false">
<opinion>此opinion可以用ajax动态加载</opinion>
</select>
$.ajax({
type:"POST",
cache:false,
url : "${ctx}/sys/user/selectTree",
async:true,
success : function(data){
$.each(data, function (i) {
$('#usertype.selectpicker').append("<option value=" + data[i].ID + ">" + data[i].NAME + "</option>");
});
$('#usertype').selectpicker('refresh');
},
});
如果需要初始化默认选中的话,可以用Ajax进行赋值
success : function(data){
var selected = new Array();
$.each(JSON.parse(data), function (i,obj) {
selected.push(obj.BASEID);
});
console.log("selected",selected)
$('#usertype').selectpicker('val', selected);//默认选中
$('#usertype').selectpicker('refresh');
}
JSON.parse的作用是:jquery each报 Uncaught TypeError: Cannot use 'in' operator to search for错误时,
在写前端的时候用jquery来遍历后台传来的json数组时候遇到这个错误:Uncaught TypeError: Cannot use 'in' operator to search for。
后来查到原因是因为:一部分浏览器后端传过来的是json对象,但是我们前端是需要Javascript的对象,所以需要做个转换JSON.parse() or jQuery $.parseJSON