Ara*_*hya 4 html jquery select
目前我有代码来过滤选择的文本,如下所示.
当我在搜索框中输入文本时,它正在过滤.但是我需要在文本框中搜索选项而不进行过滤,如下所示.
<script src="./jquery.min.js"></script>
<script>
jQuery.fn.filterByText = function(textbox, selectSingleMatch) {
return this.each(function() {
var select = this;
var options = [];
$(select).find('option').each(function() {
options.push({value: $(this).val(), text: $(this).text()});
});
$(select).data('options', options);
$(textbox).bind('change keyup', function() {
var options = $(select).empty().data('options');
var search = $.trim($(this).val());
var regex = new RegExp(search,"gi");
$.each(options, function(i) {
var option = options[i];
if(option.text.match(regex) !== null) {
$(select).append(
$('<option>').text(option.text).val(option.value)
);
}
});
if (selectSingleMatch === true && $(select).children().length === 1) {
$(select).children().get(0).selected = true;
}
});
});
};
$(function() {
$('#select').filterByText($('#textbox'), true);
});
</script>
In body tag
<select id="select" size=10>
<option value="12">12</option>
<option value="1234567890">1234567890</option>
<option value="ARADHYA">ARADHYA</option>
<option value="HI">HI</option>
<option value="APPLE">APPLE</option>
</select>
<input id="textbox" type="text">
Run Code Online (Sandbox Code Playgroud)
你的代码会发生很大的变化.
首先,select必须具有multiple属性.javascript只需要设置selected匹配选项的属性.我创建了一个小提琴,以显示它的工作,但它基本上归结为:
...
if (search == '') {
$options.prop('selected', false);
return;
}
$options.each(function() {
var $option = $(this);
$option.prop('selected', $.trim($option.text()).match(regex) !== null);
});
...
Run Code Online (Sandbox Code Playgroud)
在if语句中,当输入为空时,清除选择框.不需要再执行任何操作,因此它会立即中断事件回调(返回).然后jQuery的each函数用于遍历选项,并根据正则表达式选择或取消选择它们.