我正在使用从 rest API 填充的选择器(https://silviomoreto.github.io/bootstrap-select/examples/#live-search(。
此时,我只有 30 个条目。 但是,这个数字很快就会增长。我想从一个空的选择器开始,然后,当用户在实时搜索输入中写入一些文本时,我只用相应的项目填充选择器。
例如,如果用户写"al",那么我将用包含"al"的条目填充我的选择器。遗憾的是,此类不包含实时搜索中的事件。你能推荐另一节课吗?
任何输入都会有所帮助
问候
你将需要javascript。
下面是一个使用 jquery 的示例:
首先在 HTML 中,您需要将 select 元素包装到带有 id 的div 中,以便您可以使用表单控件类使用它的输入
<div id="my-div">
<select id="my-select" class="selectpicker" data-live-search="true"></select>
</div>
现在在javascript文件中,您需要执行以下操作
$('#my-select').selectpicker('refresh');
$('#my-div .form-control').on('keyup', function () {
//here you listen to the change of the input corresponding to your select
//and now you can populate your select element
$('#my-select').append($('<option>', {
value: 'any value',
text: 'any text'
}));
$('#my-select').selectpicker('refresh');
});
由于boostrap-select (or selectpicker)
尚不支持此功能,因此我找到了解决方法。
这不是最佳做法,但它有效。
$('#youselectpicker').on('loaded.bs.select', function (e, clickedIndex, isSelected, previousValue) {
$(".youselectpicker .bs-searchbox input").on('keyup',function(){
//place your code here
//don't forget to refresh the select picker if you change the options
})
});
我的简单jQuery实现。
jQuery("select[name='select picker name']").siblings().find("input[type='text']").keyup(function (e) {
if(e.keyCode==13){
//Code to implement ajax search
}
});
对我来说,最终只有这样:
通过结合这里的一些答案,我的解决方法是侦听单击下拉按钮,即引导程序中的"show.bs.select"事件,然后侦听输入到我放置整个选择器部分的div (my_select_outer( 中包含的输入字段中。此输入字段由单击选择器时引导程序创建。
$('#my_select').on('show.bs.select',
function(e) {
$('#my_select_outer .form-control').on('input', function() {
$('#my_select').empty();
$('#my_select').selectpicker('refresh');
let contains = $('#my_select_outer .form-control').val();
// run API call based on 'contains'
});
})
});