javascript 使用 jQuery 过滤选择框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27621726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
filter a select box with jQuery
提问by anonicode
I tried to made text input that filtering selectbox. I'm trying to fix it alot of time but it still not working well. Maybe because it is in hebrew?
我试图让文本输入过滤选择框。我试图修复它很多时间,但它仍然无法正常工作。也许是因为它是希伯来语?
HTML:
HTML:
<option value="628077"> new york</option>
<option value="244228">??? ??<option>
<option value="641332"> ??????</option>
<option value="240812"> ???????</option>
.
.
.
<option value="640375"> ??????</option>
<option value="344580"> ????</option>
<option value="440560"> ??? ???</option>
<option value="520098"> ??????</option>
</select>
jQuery:
jQuery:
<script type="text/javascript" >
$('#city').keyup(function () {
var valthis = $(this).val();
var num = 0;
$('select#DropDownList1>option').each(function () {
var text = $(this).text();
if(text.indexOf(valthis) != -1)
{ $(this).show();}
else{ $(this).hide();}
});
});
</script>
I need your help!
我需要你的帮助!
回答by Mohamed-Yousef
$('#city').keyup(function () {
var valthis = $(this).val().toLowerCase();
$('select#DropDownList1>option').each(function () {
var text = $(this).text().toLowerCase();
if (text.indexOf(valthis) !== -1) {
$(this).show(); $(this).prop('selected',true);
}
else {
$(this).hide();
}
});
});
DEMOHope it helps.
DEMO希望有帮助。
回答by Milan van Schaik
It isn't the most clean way, but something like this should work: http://jsfiddle.net/milanvanschaik/11146uxb/2/
这不是最干净的方法,但这样的方法应该可行:http: //jsfiddle.net/milanvanschaik/11146uxb/2/
$(function() {
var data = [
{ value: 628077, text: 'New York' },
{ value: 628047, text: 'Amsterdam' },
{ value: 628037, text: 'Paris' }
];
data.forEach(function(val) {
$('#select').append($('<option></option>').attr('value', val.value).text(val.text));
});
$('#city').keyup(function() {
var inputValue = $(this).val();
data.forEach(function(val) {
if(val.text.toLowerCase().indexOf(inputValue.toLowerCase()) != -1) {
$('#select>option[value="'+val.value+'"]').remove();
$('#select').append($('<option></option>').attr('value', val.value).text(val.text));
} else {
$('#select>option[value="'+val.value+'"]').remove();
}
});
});
});
Edit: Here with some Hebrew: http://jsfiddle.net/milanvanschaik/11146uxb/3/
编辑:这里有一些希伯来语:http: //jsfiddle.net/milanvanschaik/11146uxb/3/