Select2具有查询功能。只要搜索项发生更改,它就会运行查询功能。查询函数返回过滤后的数据。
我需要添加两件事: 1.我需要在Select2中添加单选按钮以启用快速过滤器 2.每当无线电值改变时,我需要重新执行查询fn
我有一个针对1的hacky解决方案。我还没弄明白2.
对于1,我使用on-select2-open事件添加包含单选按钮的div。我将div附加在.select2-drop。
中对于2,我需要一种方法来在单击单选按钮时触发查询功能。
这是HTML。
<form>
<input type='text' id='mySelId2' name='mySelName2' class='mySelClass2' style='width:300px;' value='101'/>
</form>
<div id='sel2-localcity-filter-tmpl-holder' style='display:none;'>
<div class='sel2-localcity-filter'>
<label>
<input type="radio" onclick="CityFilter.onSel2FilterClick(this)" class='localcityFilter localcityFilter_No'
name="localcityFilter" value="NoFilter" checked="checked" />Show all</label>
<label>
<input type="radio" onclick="CityFilter.onSel2FilterClick(this)" class='localcityFilter localcityFilter_Local'
name="localcityFilter" value="Local" >Only Australia</label>
</div>
</div>
和Javascript:
$(document).ready(function(){
$('#mySelId2').select2({
query: function(query){
var res = { results: CityFilter.cities };
query.callback(res);
},
initSelection: function(element, callback){
var val = element.val();
if(val==null) return;
var data = null;
for(var i=0;i< CityFilter.cities.length;i++){
if( CityFilter.cities[i].id==val){
data = CityFilter.cities[i];
break;
}
}
if(data!=null){
callback(data);
}
},
formatResult: function(item){ return (item.name); },
formatSelection: function(item){ return (item.name); },
formatNoMatches: function(){ return '<span style="color:red;">No match</span>'; },
dropdownCssClass: 'mySelClass2'
});
$('#mySelId2').on('select2-open', function(){
var selClass = 'mySelClass2';
var filterTemplateHolderId = 'sel2-localcity-filter-tmpl-holder';
var filterTmpl = $('#' + filterTemplateHolderId).html();
var existingFilterCount = $('.' +selClass+ '.select2-drop .sel2-localcity-filter').length;
if(existingFilterCount==0){
$('.' +selClass+ '.select2-drop').append(filterTmpl);
$('.' +selClass+ '.select2-drop').unbind('click'); //This click handler prevents radio from working //No I18n
}
$('.'+selClass+'.select2-drop').find('.localcityFilter_No').click();
});
});
var CityFilter = {};
CityFilter.filterEnabled = false;
CityFilter.cities = [ {id:101, country:'NE', name:'Amsterdam'},
{id:102, country:'UAE', name:'Dubai'},
{id:103, country:'SW', name:'Bern'},
{id:104, country:'AUS', name:'Sydney'},
{id:105, country:'CAN', name:'Vancouver'},
{id:106, country:'NZ', name:'Auckland'},
{id:107, country:'AU', name:'Vienna'},
{id:108, country:'GER', name:'Munich'},
{id:109, country:'SW', name:'Zurich'},
{id:110, country:'AUS', name:'Melbourne'} ];
CityFilter.onSel2FilterClick = function(el){
var jqRadio = $(el);
if(jqRadio.val()=='Local'){
CityFilter.filterEnabled = true;
}else{
CityFilter.filterEnabled = false;
}
console.log('CityFilter.filterEnabled: ' + CityFilter.filterEnabled);
};