Does jQuery autocomplete work with a dynamic array as source

前端 未结 3 1495
执念已碎
执念已碎 2021-02-14 21:04

I am currently trying to create an autocomplete with a source that is stored in a javascript variable but this variable can be updated by another function. So, what I would like

相关标签:
3条回答
  • 2021-02-14 21:44

    Just add a reset call to auto-complete in you addToTags function:

    var addToTags = function(str){
       availableTags.push(str);
       $( "#tags" ).autocomplete({
           source: availableTags
       });
    }
    
    0 讨论(0)
  • 2021-02-14 21:54

    a source that is stored in a javascript variable but this variable can be updated by another function.

    That should just work. If both the autocomplete and the updating function reference the same array, you can push new values at any time which will be used as soon as the array is evaluated next time (e.g. on keystroke).

    I would like that at each time the user updates the autocomplete field, the source field of autocomplete is generated.

    That's a different one. Yes, this needs a callback function to generate the source array dynamically, but that's simple. Have a look at the docs:

    $( "#tags" ).autocomplete({
        source: function(request, resolve) {
            // fetch new values with request.term
            resolve(availableTags);
        }
    });
    
    0 讨论(0)
  • 2021-02-14 22:06

    this is very straight forward

    $( "#tags" ).autocomplete('option', 'source', availableTags)
    

    setting availableTags array wherever needed

    0 讨论(0)
提交回复
热议问题