jqueryjquery-uiautocompletejquery-ui-autocompletejquery-tags-input

jquery tagsinput and ui autocomplete: can they work with pre-loaded source?


I have a little trouble. There's working code with tagsinput, and I know how to work with autocomplete from jquery ui.

code exampe

Neither

autocomplete' :{
    'source': tags_array
}

Nor

$("#new_tags_tagsinput").autocomplete({source: tags_array});

Seems to work.

On tagsinput site there's an example, which requires autocomplete URL, but I'd like to use loaded array, like it is on autocomplete example. I tried different options, no one worked. Is there such a way?


Solution

  • Initialize it like this:

    var tags_array = ["lorem", "ipsum", "dolar", "sit", "amet"];
    $("#new_tags").tagsInput({
        'defaultText':'add...',
        'height':'100px',
        'width':'300px',
        'autocomplete_url': '',
        'autocomplete' :{
            'source': tags_array
        }
    });
    

    JSFiddle.

    Explanation: first, as you use that array of tags as a source, there's no need to keep the same structure (i.e., comma-delimited string) - it's easier to work with a plain array from the beginning.

    Second, as the source code of the plugin shows, autocomplete_url is the setting really defining whether or not autocomplete will be utilized:

    if (settings.autocomplete_url != undefined) {
      autocomplete_options = {source: settings.autocomplete_url};
      for (attrname in settings.autocomplete) {
        autocomplete_options[attrname] = settings.autocomplete[attrname];
      }
      ...
    }
    

    In other words, you need to specify something other than null or undefined in autocomplete_url param to make it use that jQuery UI plugin. Actually, it might be a good idea for that plugin to check that param type - and setting up the autocomplete source option accordingly.