Alina85
Alina85

Reputation: 75

jQuery: populating an autocomplete on input focused

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.

Upvotes: 0

Views: 84

Answers (2)

Jitendra Yadav
Jitendra Yadav

Reputation: 896

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

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

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.

Upvotes: 1

Related Questions