jQuery UI autocomplete only works once

Asked

Viewed 261 times

2

I am working on a functionality of a Rails application where we use a Gem call Best in Place, which provides the possibility of inline editing of model attributes. But there was a need to use jQuery UI autocomplete when the user is editing some information.

Searching the OS in English, I found this question. I tried to do it the way the first guy said, thinking nay add one more 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 it no longer works and I don’t understand why. I debug and noticed that the event click is triggered normally, but this specific part of the jQuery UI autocomplete stops working after the first run.

Can anyone tell me where I’m going wrong?

  • Have you checked if the variables containerElement and textField continue with the same value ? Have you checked whether the function containerElement.data('autocomplete-uri') keeps returning the data correctly?

1 answer

1

The autocomplete function should be set only once, preferably on page loading. 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
  });
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.