自动填充以第一个字母开头

时间:2017-08-21 07:10:07

标签: javascript php jquery

我使用jQuery创建了一个具有自动完成功能的表单。

我希望自动填充显示以键入的字母开头的选项列表。

示例: - 当我输入'B'时,它应该只显示 BASIC 而不是 BASIC,COBOL,RUBY

相关代码如下:

<html lang="en">
<head>
  $( function() {
    var availableTags = ["ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran", "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python", "Ruby", "Scala", "Scheme"];
    function split( val ) {
      return val.split( /,\s*/ );
    }
    function extractLast( term ) {
      return split( term ).pop();
    }
    $( "#tags" )
      // don't navigate away from the field on tab when selecting an item
      .on( "keydown", function( event ) {
        if ( event.keyCode === $.ui.keyCode.TAB && $( this ).autocomplete( "instance" ).menu.active ) {
          event.preventDefault();
        }
      })
      .autocomplete({
        minLength: 0,
        source: function( request, response ) {
          // delegate back to autocomplete, but extract the last term
          response( $.ui.autocomplete.filter(
            availableTags, extractLast( request.term ) ) );
        },
        focus: function() {
          // prevent value inserted on focus
          return false;
        },
        select: function( event, ui ) {
          var terms = split( this.value );
          // remove the current input
          terms.pop();
          // add the selected item
          terms.push( ui.item.value );
          // add placeholder to get the comma-and-space at the end
          terms.push( "" );
          this.value = terms.join( ", " );
          return false;
        }
      });
  } );
  </script>
</head>
<body>
<div class="ui-widget">
  <label for="tags">Tag programming languages: </label>
  <input id="tags" size="50">
</div>
</body>
</html>

我哪里出错了?

1 个答案:

答案 0 :(得分:0)

您需要将以下代码替换为您的代码

 source: function( request, response ) {
          var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( request.term ), "i" );
          response( $.grep( tags, function( item ){
              return matcher.test( item );
          }) );
      }

有关详细信息,请参阅链接http://api.jqueryui.com/autocomplete/#example-1