Select2 提供了一个可自定义的选择框,该框支持搜索、标记、远程数据集、无限滚动以及许多其他常用选项。
Select2 是基于 jQuery 的选择框的替代品。它支持搜索,远程数据集和结果分页。
Quick Start
引用jquery,select2
<script type="text/javascript" src="../../scripts/jquery-1.10.1.min.js"></script>
<script src="../../scripts/select2/js/select2.full.min.js" type="text/javascript"></script>
<script src="../../scripts/select2/js/i18n/zh-CN.js" type="text/javascript"></script>
定义需要绑定的select
<select id="wlxx" class="form-control" name="wlxx" style="max-width: 150px; width: 150px;"></select>
js调用
$("#wlxx").select2({
placeholder:"",
minimumInputLength: 1,
maximumInputLength:100,
allowClear:true,
width:300,
language: "zh-CN",
ajax: {
url: './qrcode!searchWlxx.action',
contentType : "application/json",
dataType: 'json',
type:'get',
delay: 500,
async:false,
timeout : 3000, //超时时间设置,单位毫秒
data: function (params) {
return {
queryStr:encodeURI(encodeURI(params.term).replace(/\+/g,'%2B')),
pageIndex:params.page,
pageSize:10
}
},
processResults: function (data,params) {
params.page = params.page || 1;
var results = [];
$.each(data.list, function (i, v) {
var o = {};
o.id = v.wlxxid;
o.text=v.wlmc;
o.wlxxid=v.wlxxid;
o.wlmc = v.wlmc;
o.wlbh=v.wlbh;
results.push(o);
});
return {
results: results,
pagination: {
more: (params.page * 10) < data.total //每页10条数据
}
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; },
templateResult: function formatRepo(repo){
if(!repo.id){
return "加载中...";
}
return '<span style="color:black;font-weight:bold;">' + repo.wlmc + '</span></br><span> 编号:' + repo.wlbh + '</span> '},
templateSelection: function formatRepoSelection(repo, container){
if(!repo.id){
return "请选择商品";
}
return repo.text
}
});
要求的JSON格式:
{
"total":6381,
"list":[
{"wlxxid":"WLXX20140505092138953","wlbh":"03010109906018750201","wlmc":"12.00-20-20PR[M9088]GOODRIDE(好运)","RN":1},
{"wlxxid":"WLXX20140731150150987","wlbh":"03010437201037100201","wlmc":"165/60R14PR[RP28]H GOODRIDE(好运)无内","RN":10}
]
}