Wednesday, March 27, 2013

jQuery autocomplete

Here is a simple way to implement an 'autocomplete' text field:

Define a function to use as a typewatch timer:

var typewatch = (function(){
  var timer = 0;
  return function(callback, ms){
    clearTimeout (timer);
    timer = setTimeout(callback, ms);
  }
})();

Then use the timer in a .keyup() jQuery event listener.

$('#text-field').keyup(function(e) {
    typewatch(function () {
        tmpLen = $('#text-field').val().length;
        if( tmpLen > 2 || tmpLen == 0 ) { // also searches when the field is cleared with backspace
              getAutoComplete();  // or any other action
        }
    }, 500);
});

The listener will trigger a call to getAutoComplete() when the length of the text in the field is greater than 2 characters, or 0 characters for when the field is cleared.

Adjusting the > 2 characters or 500ms timeout will fine tune the behavior.