Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery UI: Autocomplete on multiple fields, use different sources

I've got a page with multiple forms that load via ajax. Each form includes one text field that needs to autocomplete. Each text has a data attribute for its autocomplete source. For instance:

<input type="text" class="district_name" data-autocomplete-source="['foo','bar','baz']" ... />

There could be many of these, they would belong to different forms and modify different records, but the autocomplete field will have the same class.

If I call autocomplete on these like so...

$('input.district_name').autocomplete({
  source: $('input.district_name').data('autocomplete-source')
});

... then jQuery UI merges the sources from each field to one master list. I tried instead calling...

$('input.district_name').autocomplete({
  source: $( this ).data('autocomplete-source')
});

... which I was hoping would grab the source from its own parent, but that didn't work at all. Because these fields are added to the page via ajax I don't know in advance what their individual IDs will be, only the class. There could be many or few, it just depends on what the user is doing.

How would you solve this?

like image 548
Andrew Avatar asked Mar 07 '12 17:03

Andrew


1 Answers

You need to call autocomplete separately for each element:

$('input.district_name').each(function() {
    $(this).autocomplete({
        source: $(this).data('autocomplete-source')
    });
});
like image 138
SLaks Avatar answered Oct 02 '22 17:10

SLaks