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

自闭症网瘾萝莉.ら 提交于 2019-12-12 11:05:41

问题


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.


回答1:


Use the focus event instead:

focus: function (event, ui) {
    event.preventDefault();
}


来源:https://stackoverflow.com/questions/16701589/how-to-prevent-update-of-input-element-when-an-item-is-selected-in-a-jqueryui-au

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!