1

我正在为我的表单使用自动完成功能。我使用下面的 jquery 脚本来实现自动完成功能。

<script>
$( "#autocomplete" ).autocomplete({
  source: [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby" ]
});
</script>

上面代码的 o/p 是它获取与我们在输入框中输入的字母相关的所有单词。例如:如果我输入“C”,那么它会获取所有包含 C 的单词。但我希望单词单独以 C 开头。

HTML部分是:

<label for="tags">Tags: </label>
  <input id="tags" />

请任何人对此提供帮助....谢谢

4

2 回答 2

3

HTML部分:

 <label for="tags">Tags: </label>
 <input id="tags" />

替换为:

<label for="autocomplete">Tags: </label>
  <input id="autocomplete" />

和 Js 部分

 <script>
 $( "#autocomplete" ).autocomplete({
    source: [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby" ]
 });
</script>

替换为:

<script>
var tags = [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby" ];
 $( "#autocomplete" ).autocomplete({
   source: function( request, response ) {
      var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( request.term ), "i" );
      response( $.grep( tags, function( item ){
          return matcher.test( item );
      }) );
  }
 });

它会工作

演示

于 2013-09-17T09:43:17.767 回答
1

请尝试以下代码:

<title>Autocomplete</title>
<body>
 <label for="tags">Tags: </label>
 <input id="tags">
</body>

Javascript:

var availableTags = [
 "ActionScript",
 "AppleScript",
 "Asp",
 "BASIC",
 "C",
 "C++",
 "Clojure",
 "COBOL",
 "ColdFusion",
 "Erlang",
 "Fortran",
 "Groovy",
 "Haskell",
 "Java",
 "JavaScript",
  "Lisp",
  "Perl",
  "PHP",
 "Python",
 "Ruby",
 "Scala",
 "Scheme"
];
$( "#tags" ).autocomplete({
   source: function( request, response ) {
    var matches = $.map( availableTags, function(tag) {
      if ( tag.toUpperCase().indexOf(request.term.toUpperCase()) === 0 ) {
       return tag;
     }
    });
   response(matches);
 }
});

我有copied这个来自 jQuery 论坛的脚本。

下面是相同的JsFiddle

于 2013-09-17T09:59:13.627 回答