javascript 在下拉菜单中搜索的工作代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21085845/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 20:01:09  来源:igfitidea点击:

Working code to search within dropdown menu

javascriptdrop-down-menu

提问by user3187352

Someone helped me with this earlier, but there is one problem and I already closed that question. I do not want to use JQuery. The following code works, it allows you to search a dropdown menu:

早些时候有人帮我解决了这个问题,但有一个问题,我已经结束了那个问题。我不想使用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>

Here is the problem.

这是问题所在。

It is only limited to the matching first letters of the first word. So if you typed in Superfor Super Man, it would work. But if you typing with Manit will not show. Is there a way to make it match the whole string for a matching value? Thanks.

它仅限于匹配第一个单词的第一个字母。所以如果你输入Super超人,它会起作用。但是如果你用Man它打字就不会显示。有没有办法让它匹配整个字符串的匹配值?谢谢。

回答by A Paul

I have created a fiddle please check. http://jsfiddle.net/wLzs4/3/

我已经创建了一个小提琴请检查。 http://jsfiddle.net/wLzs4/3/

I have used the indexOf javascript function for your case.

我已经为您的案例使用了 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;
    }