The jQuery UI toolbox gives you a lot of new controls to play around with if you are already using the awesome jQuery library, one of which it the very useful autocomplete control.

Essentially “Autocomplete enables users to quickly find and select from a pre-populated list of values as they type, leveraging searching and filtering. Any field that can receive input can be converted into an Autocomplete, namely, <input> elements, <textarea> elements, and elements with the contenteditable attribute.

By giving an Autocomplete field focus or entering something into it, the plugin starts searching for entries that match and displays a list of values to choose from. By entering more characters, the user can filter down the list to better matches.”

The problem arises when something is pre-populated in the autocomplete element, i.e. something had previously been selected. When you click on the control to start searching, your newly entered text simply appends on to the end of the existing text, resulting in a gobbledygook search!

To combat this we essentially need to select all text when the autocomplete box is called upon, and it turns out to do this we need to work with the mouse up event.

In practice, the code to achieve this select all text on entering the autocomplete search box looks like this:

<div class="ui-widget">
  <label for="tags">Tags: </label>
  <input id="tags">
$(document).ready(function() {
    var availableTags = [
    $( "#tags" ).autocomplete({
      source: availableTags
    }).on('mouseup', function() {

As you can see, we add the mouseup event monitor at input initialization, and with this now in place, every time the user clicks on the control any existing text is automatically selected – meaning that as soon as the user starts entering text, whatever was there previously will now be lost. Victory!

laptop click with mouse

Related Link: