2

I'm new to Javascript and I'm trying to create an array to use for Autocomplete plugin. The plugin is working perfectly with the following code:

countries = new Array();
countries[0]='United States';

'use strict';


$('#autocomplete').autocomplete({
    lookup: countries,
    minChars: 2,
    onSelect: function (suggestion) {
        //I will put something here soon.
    }
});

But when I try to create an array from a text file, I can't create the array even though the code seems fine.

$.get('test.txt', function(data){
   var array = data.split(',');
   var i = 0;
   array.forEach(function(insert) {
   countries[i]=insert;
   i++;
   });
});

Any reason why it would not insert the data in the text file to the countries array? It seems to me that everything I do should work. By the way, no worries, the test.txt file is just fine (United States,Mexico).

Thanks ahead and have a great day.

2
  • Possible duplicate stackoverflow.com/questions/10682901/… Commented Apr 30, 2014 at 12:18
  • Can you not have the text file as a javascript array? I normally use Ajax to bring in a .js file which is formed as a Javascript Array already. Commented Apr 30, 2014 at 12:21

1 Answer 1

1

$.get is an asynchronous function, so by the time autocomplete method is executed, countries would have got no element from the file. So, move the autocomplete function to the callback of $.get like this

$.get('test.txt', function(data) {
    var array = data.split(',');
    $('#autocomplete').autocomplete({
        lookup: array,
        minChars: 2,
        onSelect: function(suggestion) {
            //I will put something here soon.
        }
    });
});

Also, you don't have to populate countries like you did in the question. You can simply pass the array returned by JavaScript's split function, as it is.

Sign up to request clarification or add additional context in comments.

9 Comments

Shouldn't this work assuming that $.get is put above the autocomplete function? I've done something similar using $.ajax instead of get and it works ok.
@Scironic Even if it is above the autocomplete, since the execution is asynchronous, countries will be filled only after executing autocomplete
@thefourtheye. So in an example where I have a js file with an array (tags = [1,2,3,4,etc]) which is pulled in through an Ajax request and then the autocomplete function is run after - what's happening differently?
@Scironic Can you create a sample fiddle, so that I can look at the flow of control?
@Scironic Ah, your case is different. You are executing autocomplete in done. jQuery makes sure to execute done only after getting response from the AJAX call. That is why your code works :-)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.