当键入3个或更多字符时限制jQuery的自动完成功能

时间:2014-09-11 18:19:57

标签: jquery html

我正在使用jQuery的自动完成小部件:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>autocomplete demo</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script type="text/javascript" src="my_code.js"></script>
</head>
<body>

<label for="autocomplete">Select a programming language: </label>
<input id="autocomplete">

<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 );
          }) );
      }
});

</script>

<p>Search term is: <span id="demo"></span></p>

</body>
</html>

如果自动填充表单中有3个或更多字符,我想将其限制为仅建议值。有任何想法吗?感谢。

2 个答案:

答案 0 :(得分:2)

使用指定的minLength选项初始化自动完成:

$(".selector").autocomplete({ minLength: 3 });

答案 1 :(得分:1)

只需像这样添加minLength:

$( "#autocomplete" ).autocomplete({minLength: 3, source: tags});