本文使用的select2版本为select2 4.0.2
数据库中的表格信息如下,month字段包含了年、月信息。使用select2插件作为筛选框,以年度和月份信息筛选表格数据。年度和月份这两个筛选框作为联动的筛选框。
HTML 筛选框部分
<span class="c_lable" >年度</span>
<select id="selectYear" class="form-control select2" placeholder=""></select>
<span class="c_lable" >月份</span>
<select id="selectMonth" class="form-control select2" placeholder=""></select>
JavaScript部分
使用ajax获取到上述表格month列的数据,对数据进行处理。处理的数据放selectData中,selectData如下,其中key为年度,value为当前年度对应的可选月份。$("#selectYear").on("change",function(e){})年度更新的时候,清空月份筛选框,重新赋值。
var selectData={};
$(function(){
//初始化选择框
$.ajax({
type:"get",
url:"${ctx}/Table/MonthHistory/getSelect",
dataType:"json",
contentType:"application/json",
success:function(data){
var json =JSON.parse(data);
//console.log(data);
json.forEach(function(item,index){
var y=item.split('.')[0];
var m=item.split('.')[1];
if(!selectData[y])
{
selectData[y]=[];
selectData[y].push(m);
}
else
{
selectData[y].push(m);
}
});
var keys = [];
for (var p1 in selectData) {
if (selectData.hasOwnProperty(p1))
keys.push(p1);
}
$("#selectYear").select2({
data: keys,
placeholder:'请选择年度',
language: "zh-CN",
allowClear: true,
width:'150px'
});
$("#selectMonth").select2({
data:selectData[$("#selectYear").select2("data")[0].id],
placeholder:'请选择月度',
language: "zh-CN",
allowClear: true,
width:'150px'
})
},
error:function(data){
console.log('筛选框获取数据出错啦!');
}
});
//初始化表格
initTable();
});
//年度更新的时候
$("#selectYear").on("change",function(e)
{
var arr=[];
if($("#selectYear").select2("data").length!=0)
arr=selectData[$("#selectYear").select2("data")[0].id];
console.log(arr);
//清空月份
$("#selectMonth").select2().empty();
$("#selectMonth").select2({
data:arr,
placeholder:'请选择月度',
language: "zh-CN",
allowClear: true,
width:'150px'
}) ;
});