Skip to content

Instantly share code, notes, and snippets.

@jtsaito
Last active August 29, 2015 14:13
Show Gist options
  • Save jtsaito/1d572909a6555ba85855 to your computer and use it in GitHub Desktop.
Save jtsaito/1d572909a6555ba85855 to your computer and use it in GitHub Desktop.
Note on jQuery's autocomplete plugin

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.

Links

The jQuery Project (2015): jQuery UI Documentation. Salman Arshad (2013): 5 jQuery UI Autocomplete Examples

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment