jQuery's Autocompletion plugin comes with jQuery UI. The plugin autocompletes "any field that receives an input." Below is an example from the malt-mate app in coffee script. It fetches the autocomplete values from remote. Moreover, the code does away with the default behaviour of displaying values for labels in the <input type="text">
. (By default, labels are displayed on select but values are displayed on focus.)
<input id="distillery-autocomplete">
<input hidden=true id="distillery-autocomplete-value" type="text" name="distillery-id">
$("#distillery-autocomplete").autocomplete(
delay: 500 # delay between attempts to fetch data
source: (request, response) ->
url = "/api_v1/distilleries?q=#{request.term}"
$.getJSON(url, (data) ->
labels_and_values = _.map(data, (distillery) ->{ label: distillery.name, value: distillery.id } )
response(labels_and_values)
).error ->
response []
focus: (event, ui) ->
event.preventDefault() # prevent from updating the textbox
$(this).val(ui.item.label) # don't display default item.value all the time
select: (event, ui) ->
event.preventDefault() # prevent from updating the textbox
$(this).val(ui.item.label)
$("#distillery-autocomplete-value").val(ui.item.value)
)
Yes, there is some Underscore mixed in here.
The jQuery Project (2015): jQuery UI Documentation. Salman Arshad (2013): 5 jQuery UI Autocomplete Examples