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

use*_*352 3 javascript drop-down-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>
Run Code Online (Sandbox Code Playgroud)

这是问题所在.

它仅限于匹配第一个单词的第一个字母.所以,如果你输入Super超人,那就行了.但如果你输入Man它将不会显示.有没有办法让它匹配整个字符串的匹配值?谢谢.

A P*_*aul 7

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

我已经为你的情况使用了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;
    }
Run Code Online (Sandbox Code Playgroud)