Autocomplete of jQuery UI only works once

2

I'm working on a feature of a Rails application where we use a gem called Best in Place , which provides the possibility of inline editing attributes of a model. But there arose the need to use autocomplete of jQuery UI when the user is editing some information.

Looking at the English OS, I found this question . I tried to do the way the first guy said, thinking not to add another dependency to the application. My JavaScript code looks like this:

$('#edit_objeto').on('click', function(event) {
  var self = $(this);
  var containerElement = $("#best_in_place_processo_9_objeto");
  var textField = containerElement.find("form input[type=text]");

  // Aqui está a parte problemática...
  textField.autocomplete({
    autoFocus: true,
    source: containerElement.data('autocomplete-uri'),
    minLength: 2
  });

  return false;
});

When I test in the browser, it works, but only the first time. The second time on, it does not work anymore and I do not understand why. I debugged and noticed that the click event fires normally, but that particular part of the jQuery UI autocomplete stops working after the first execution.

Can anyone tell me where I'm wrong?

    
asked by anonymous 04.12.2015 / 13:03

1 answer

1

The autocomplete function must be defined only once, preferably when loading the page. In your code it is linked to the click event, and is reset each time the #edit_object element is clicked, which generates the error.

If you are not going to use the containerElement and textField variables elsewhere, you replace your function with:

$(function(){
    $('#id_do_input').autocomplete({
    autoFocus: true,
    source: containerElement.data('autocomplete-uri'),
    minLength: 2
  });
});
    
08.12.2015 / 03:41