Javascript 要在下拉菜单中搜索的工作代码
早些时候有人帮过我,但有一个问题,我已经解决了这个问题。我不想使用Javascript 要在下拉菜单中搜索的工作代码,javascript,drop-down-menu,Javascript,Drop Down Menu,早些时候有人帮过我,但有一个问题,我已经解决了这个问题。我不想使用JQuery。以下代码起作用,它允许您搜索下拉菜单: <html> <head> <script type="text/javascript"> function searchSel() { var input = document.getElementById('realtxt').value.toLowerCase(), len
JQuery
。以下代码起作用,它允许您搜索下拉菜单:
<html>
<head>
<script type="text/javascript">
function searchSel()
{
var input = document.getElementById('realtxt').value.toLowerCase(),
len = input.length,
output = document.getElementById('realitems').options;
for(var i=0; i<output.length; i++)
if (output[i].text.toLowerCase().slice(0, len) == input)
output[i].selected = true;
if (input == '')
output[0].selected = true;
}
</script>
</head>
<body>
<form>
search <input type="text" id="realtxt" onkeyup="searchSel()">
<select id="realitems">
<option value="">select...</option>
<option value="1">Power hungry</option>
<option value="2">Super man</option>
<option value="3">Hyperactive</option>
<option value="4">Bored</option>
<option value="5">Human</option>
</select>
</form>
</body>
</html>
函数searchSel()
{
var input=document.getElementById('realtxt').value.toLowerCase(),
len=输入长度,
输出=document.getElementById('realitems')。选项;
对于(var i=0;i我已经创建了一个小提琴,请检查。
我在您的案例中使用了indexOf javascript函数
function searchSel()
{
var input = document.getElementById('realtxt').value.toLowerCase();
len = input.length;
output = document.getElementById('realitems').options;
for(var i=0; i<output.length; i++)
if (output[i].text.toLowerCase().indexOf(input) != -1 ){
output[i].selected = true;
break;
}
if (input == '')
output[0].selected = true;
}
函数searchSel()
{
var input=document.getElementById('realtxt').value.toLowerCase();
len=输入长度;
输出=document.getElementById('realitems')。选项;
对于(var i=0;i