我有这个 HTML 下拉列表:
<form>
<input type="text" id="realtxt" onkeyup="searchSel()">
<select id="select" name="basic-combo" size="1">
<option value="2821">Something </option>
<option value="2825"> Something </option>
<option value="2842"> Something </option>
<option value="2843"> _Something </option>
<option value="15999"> _Something </option>
</select>
</form>
我需要使用 javascript 进行搜索。 这就是我现在拥有的:
function searchSel() {
var input=document.getElementById('realtxt').value.toLowerCase();
var output=document.getElementById('basic-combo').options;
for(var i=0;i<output.length;i++) {
var outputvalue = output[i].value;
var output = outputvalue.replace(/^(\s| )+|(\s| )+$/g,"");
if(output.indexOf(input)==0){
output[i].selected=true;
}
if(document.forms[0].realtxt.value==''){
output[0].selected=true;
}
}
}
该代码不起作用,而且可能不是最好的。
任何人都可以告诉我如何使用纯 JavaScript 在下拉菜单中进行搜索,当我按 Enter 时找到我想要的项目,如果我再次按 Enter 给出下一个结果?
最佳答案
这是固定代码。它仅搜索第一次出现的位置:
function searchSel() {
var input = document.getElementById('realtxt').value;
var list = document.getElementById('select');
var listItems = list.options;
if(input === '')
{
listItems[0].selected = true;
return;
}
for(var i=0;i<list.length;i++) {
var val = list[i].value.toLowerCase();
if(val.indexOf(input) == 0) {
list.selectedIndex = i;
return;
}
}
}
不应在 for 循环之外检查空文本。 此外,此代码将进行部分匹配,即如果您输入“A”,它将选择“Artikkelarkiv”选项。
关于javascript - 搜索下拉菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1130699/