jQuery UI: Autocomplete on multiple fields, use different sources
Asked Answered
S

1

6

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?

Stinson answered 7/3, 2012 at 17:10 Comment(0)
S
9

You need to call autocomplete separately for each element:

$('input.district_name').each(function() {
    $(this).autocomplete({
        source: $(this).data('autocomplete-source')
    });
});
Scum answered 7/3, 2012 at 17:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.