0

I cannot figure out how to populate the autocomplete list of an input dynamically. Here is some test code:

<input id="AnlNr">

[....]

var AnlNrTags = ["five","six","seven","eight"];

jQuery( "#AnlNr" )
    .autocomplete({
        source: AnlNrTags,
        }
     })

     .focus(function() {
         AnlNrTags = ["one","two","three","four"];
     });

Autocomplete populates "five","six","seven","eight". OK. Now when the input is focused, I wanted it "one","two","three","four", but the autocomplete selections are still like before. Seems the autocomplete widget isn't designed to re-evaluate the autocomplete source after initialization.

How can I change my autoselection list in .focus?

Thx

Alina.

Alina85
  • 75
  • 7

2 Answers2

1

To change the source property of the autocomplete after initialisation, you need to call it with the option property. Try this:

.focus(function() {
    AnlNrTags = [ "one", "two", "three", "four" ];
    jQuery("#AnlNr").autocomplete('option', 'source', AnlNrTags);
})

Example fiddle

Note that your pattern is a little off. Becuase you are changing the source as soon as the input element is focused means that the first set of options five, six, etc will never be seen.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Jep, that was exactly what my sample was supposed to show. the new values assigned in the .focus handler never make it into the autocomplete list. Thanks for your sample code, looks very promising, will try it tonight. – Alina85 Jul 11 '15 at 13:30
0

Try this one,

$(function() {
    $('#in1').autocomplete({
        source: ["five","six","seven","eight"],
        minLength: 0
    }).focus(function(){
        var newtag = [ "one", "two", "three", "four" ];
        $("#in1").autocomplete('option', 'source', newtag);           
       $("#in1").data("autocomplete").search($(this).val());
    });
});

DEMO

Look into second demo where merging both values. DEMO-2

Jitendra Yadav
  • 896
  • 1
  • 6
  • 14