jQuery autocomplete - update options on dynamically created elements

Posted by Ian Robinson on Stack Overflow See other posts from Stack Overflow or by Ian Robinson
Published on 2010-03-29T19:35:32Z Indexed on 2010/03/30 1:33 UTC
Read the original article Hit count: 982

Background

The user enters values into multiple inputs on the page. Think of entering a list of widgets for sale. The user would select the type of a widget from a drop down. Then enter the name of the Widget vendor, and then the actual name of the widget. These UI elements would all appear as one row. The user is able to click an "add another widget" link and a new row is created.

The two input elements have autocomplete functionality attached to them using the DevBridge jQuery plugin. It suggests the name of the vendor and the name of the widget.

I have recently wired up the logic to filter the name of the widget based on the name of the vendor you entered. This means setting the (custom) vendorName parameter when attaching the autocomplete plugin so it can be passed to the server side to retrieve the widget names for that vendor that match the name the user entered.

To achieve this functionality I'm dynamically attaching the autocomplete functionality to the second element (the widget name text box) when it receives focus. Here is an example:

$('.autocomplete-widget').live('focus', function () {
    $(this).autocomplete({ serviceUrl: '/something.ashx', params: { type: 'widget', vendorName: $(this).parent().prev().find('.autocomplete-vendor').val()} });
});

Problem

At first glance, this looks to function quite well. However I started noticing some inconsistencies, and upon inspection, I found out that the call to the server is actually happening several times in some cases.

Each time the widget name input element receives focus the autocomplete functionality is attached. And what I'm seeing is that the call to the server is made in proportion to how many times the input element has gained focus.

I'd like to avoid making the call more than once, but retain the ability to attach (or update) the autocomplete functionality "on focus".

I've tried to use the autocomplete 'setOptions' method but have only been able to get it to work with the static elements, not the dynamically created elements.

Question

Is there a way I can clear out the autocomplete functionality before I attach another one?

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about jquery-plugins