Home · Posts
Using jQuery's Autocomplete for Text Input Suggestions
Dec. 3, 2010

Sometimes when making a web form, you want an input to be open-ended, but still have suggested values that are easy to select. This is useful when some values for the field are very common.

For example: What's your favorite color? Most people can complete this input with just two clicks, but you can still type fuchsia if you want.

This looks a lot like autocomplete. So, when I was implementing this feature, jQuery UI's autocomplete functionality seemed like an obvious tool to use (I was already using jQuery).

Indeed, this worked, and the code to make it work was simple. But it took me a little longer than it should have to figure out the details. Hopefully this post will save you some trouble.

// Use a "callback" data source. See http://docs.jquery.com/UI/Autocomplete for details.
$('#my_input').autocomplete({source:function(req, resp){resp(['blue', 'green', 'red']);}, minLength:0, delay:0});

// We want to show our suggestions as soon as the user focuses the field. So
// in addition to setting minLength to 0 characters and delay to 0 milliseconds (above),
// bind autocomplete to activate on the input's 'focus' event.

Of course, you can do things like vary the suggested values depending on the user or other context.

That's all! This blog post was: