Jason Bourne Jason Bourne - 6 months ago 19
Linux Question

Jquery: Code not executing on page load in rails

This is for jquery UI autocomplete in my rails application. In one javascript file, I have an array of objects containing the names of all US states, like so.

var allStates = [
{
"name": "Alabama",
"abbreviation": "AL"
},
{
"name": "Alaska",
"abbreviation": "AK"
},
];


Here are my javsacript functions. Originally I had these in a different JS file but even putting it at the bottom of the same file under all of the objects doesn't work. The goal of these functions is to convert all of the names of the states from the array of objects to an array like var Statesarray= ["Alabama", "Alaska"];

var statesArray = [];
$(document).on('ready page:load', function(){
function singArray() {
for (var i = 0; i <allStates.length; i ++) {
statesArray.push(allStates[i].name);
}
return statesArray;
}
})

function updateStateSearch() {
$("#state-field").autocomplete({
source: statesArray
});
}


However, when I load my page, the conversion of all of the values into the array (the form it needs to be in to be used by jquery UI), does not seem to be working. For example, I know it doesn't because when I load the page and type something like statesArray.length;, the value returned is 0, even though they were all supposed to be pushed to that array on the page load.

NOTE: The updateStateSearch function for the autocomplete is executed on this event:

<%= f.text_field :state, :id => "state-field", :onkeydown=>"updateStateSearch()" %>


To be frank- why isn't my code working?

Answer

on page load, you're just defining the function singArray which isn't being called anywhere. If you want the array to be loaded on page load, just remove the definition for singArray:

$(document).on('ready page:load', function(){
    for (var i = 0; i <allStates.length; i ++) {
        statesArray.push(allStates[i].name);
    }
});

If you want to populate the array at some other time after page load, call singArray there - for example:

function updateStateSearch() {
    $("#state-field").autocomplete({
        source: singArray();
    });
}