如何在jQuery自动完成中键入3个字符时调用函数

时间:2014-09-12 16:39:39

标签: javascript jquery html

我想要一组"标签"当用户在自动填充表单中键入3个字符时进行更新。基本上,我想这样做

<!-- when 3 characters are typed in autocomplete form, make this $.get call -->
var tags = [];
$.get("myaspscript", function(data, status) {
    tags = data.split(", ");
    $(result).html( data );
});

我该怎么做?谢谢你的帮助。

<body>

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

<script>
var tags = [];
$.get("myaspscript", function(data, status) {
    tags = data.split(", ");
    $(result).html( data );
});

$( "#autocomplete" ).autocomplete({
  minLength: 3,

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

</script>

</body>

1 个答案:

答案 0 :(得分:0)

不确定自动填充是否有选项,但您可以手动检查:

  $('#autocomplete')
    .bind('keypress keyup', function(e){
      if ($(this).val().length < 3 ) return;
      //make your $.get call
    });
  });