Skip to content

Instantly share code, notes, and snippets.

@brianmario
Created January 22, 2009 06:34
Show Gist options
  • Save brianmario/50450 to your computer and use it in GitHub Desktop.
Save brianmario/50450 to your computer and use it in GitHub Desktop.
Account Auto Suggest
// HTML Response Autocompleter plugin
jQuery.fn.autocompleteme = function(options) {
return $(this).each(function() {
var input = $(this);
var settings = jQuery.extend({
url: '/accounts/autocomplete',
delay: 250,
resultsSelector: input.selector+'.results'
}, options);
var req = null;
var timeout = null;
var cache = {};
input.keyup(function(e) {
e.preventDefault();
clearTimeout(timeout);
timeout = setTimeout(function() {
clearTimeout(timeout);
var formVal = input.val();
if (formVal !== '') {
// Cancel the pending request so we don't have to wait for it to come back
if (req !== null && req.readyState < 4) {
req.abort();
}
if (!cache[formVal]) {
req = $.get(settings.url, 'q='+formVal, function(data) {
cache[formVal] = data;
if (input.val() === formVal) {
input.parent('form').find(settings.resultsSelector).html(data);
}
}, 'html');
} else {
input.parent('form').find(settings.resultsSelector).html(cache[formVal]);
}
} else {
input.parent('form').find(settings.resultsSelector).html('');
}
}, settings.delay);
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment