Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent update of input element when an item is selected in a jQueryUI autocomplete list?

I have the following jQueryUI autocomplete

$('#clientSearch').autocomplete({
  source: function (request, response) {

    var url = window.apiUrl + '/clients?searchText=' + request.term;

    var request = $.ajax({
      url: url,
      type: 'GET',
      dataType: "json",
      cache: false,
      contentType: 'application/json; charset=utf-8'
    });

    request.done(function (clientList) {
      response($.map(clientList, function (client) {
        return {
          label: client.lastName + ', ' + client.firstInitial + '. ' + client.sex + '/' + client.age,
          value: client.id
        }
      }));
    });

    request.fail(function (jqXHR, textStatus, errorThrown) {
      response(
      {
        label: 'Error retrieving clients',
        value: null
      }
      );
    });

  },
  minLength: 2,
  select: function (event, ui) {
    event.preventDefault();
    getClient(ui.item.value);
  }
});

After the autocomplete list is display when the down arrow is pressed to move focus/highlight to item #1 the item.value is displayed in the input element where the user typed the search criteria.

From what I have read adding event.preventDefault() in the select event, as done in the code above, should prevent the item.value from being inserted into the input element.

However, the item.value is still being inserted and a breakpoint in the select event is not hit until the highlighted item is "selected" w/ ENTER.

I would like the original search text to remain in the input element as the highlight is moved between the items in the autocomplete list.

like image 211
ChrisP Avatar asked May 22 '13 21:05

ChrisP


1 Answers

Use the focus event instead:

focus: function (event, ui) {
    event.preventDefault();
}
like image 162
Andrew Whitaker Avatar answered Oct 02 '22 17:10

Andrew Whitaker