Adam Thompson
Adam Thompson

Reputation: 467

Assigning hidden variable in a function within a function

I have javascript code similar to the following, however when I try to use 'myVar' within foo(), its value is undefined. I've also tried passing the variable into bar() and assigning it directly, but will not pass by reference.

function foo() { 
   bar();
   var myVar = document.getElementById('coords').value;
   // myVar should now be (40.7143528, -74.0059731)
   alert(myVar); // returns blank

   var request = {
    location: myVar,
    radius: 500,
    types: [type] //previously defined 
   };

   //Then send a search request to Google...
}

function bar() {
   geocoder.geocode( {'address':address}, function(results, status) {

      document.getElementById('coords').value = results[0].geometry.location;
      // Let's say the location is NYC (40.7143528, -74.0059731)

     alert(document.getElementById('coords').value); //returns the correct value
     // however, this pops up after the pop up in function foo() 

   });
}

with the following HTML

<input type="hidden" id="coords" name="coords"/>

The real code is using Google Maps API if that makes a difference:

Upvotes: 0

Views: 105

Answers (2)

Explosion Pills
Explosion Pills

Reputation: 191789

bar runs asynchronously because geocoder does. That means that

document.getElementById('coords').value = results[0].geometry.location;

actually executes after

var myVar = document.getElementById('coords').value;

You can't use ajax this way. All of your work that relies on results/status has to be done in the callback.

Upvotes: 1

Travis J
Travis J

Reputation: 82327

jsfiddle Demo

Runs fine for me. Make sure when defining your functions to actually use function in front of the definition.

function foo() { 
 bar();
 var myVar = document.getElementById('coords').value;
}

function bar() {
 document.getElementById('coords').value = 4;
}

foo();

Upvotes: 1

Related Questions