jQuery UI Autocomplete: How to clear the Search Text after Selection Programming 24 MAR 2015

jQuery UI is a curated set of user interface interactions, effects, widgets, and themes built on top of the jQuery JavaScript Library. One of the useful widgets in the collection is the Autocomplete widget, which enables users to quickly find and select from a pre-populated list of values as they type, leveraging searching and filtering.

Easy to implement, works like a charm, the question then is how does one clear the search text after the user makes a selection from the autocomplete list?

Simply setting the value to ” in the select event function declaration won’t work out of the box, because the select event occurs before the field is actually updated – in other words, your change will be lost when the textbox is updated. To prevent this from happening, you essentially need to cancel the event to stop it from running to completion – in other words, return false.

So in practice, your declaration should look like this:

<div class="ui-widget">
  <label for="tags">Tags: </label>
  <input id="tags">
</div>
$(document).ready(function(){
var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "Scheme"
    ];
    $( "#tags" ).autocomplete({
      source: availableTags,
      select: function(event, ui) {
          alert(ui.item.value);
          this.value = "";
          return false;
      }
    });
});

And that is all there is to clearing the search term from the Autocomplete box after a user selects something!

pink convertible bug - volkswagen beetle

Related Link: http://jqueryui.com/autocomplete/

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.