tags:

views:

247

answers:

2

I'm using the following code to populate a 2nd select box with cities:

  jQuery('#country').live("change", function(){ 
    populateCityListBox();
    alert(jQuery("select#city").val());
  }); 

- - - -  - - - - - - - - - - -

  function populateCityListBox()
  {

    jQuery.get("my/path/myfile.php", { instance: 'getCitiesByCountry', countryID: jQuery("select#country").val(), brandID: $_GET('brandID') },
      function(data)
      {
          var options = '';
          for (var i = 0; i < data.length; i++) {
            if (i == 0)
              options += '<option selected value="' + data[i].city + '">' + data[i].city + '</option>';
            else
              options += '<option value="' + data[i].city + '">' + data[i].city + '</option>';

          }

          jQuery("select#city").append(options);
      },"json");
  }

Populating the list box works fine. But the alert does not output the new city (after country selection). Can this be a binding problem? I thought using $.live solved all this.

It looks like the alert() is triggered before the city list box is updated. What am I doing wrong?

+1  A: 

Steven, you are exactly right. The code:

alert(jQuery("select#city").val());

is executing before your get() request has returned with a response from the server. The callback function you defined for populating your city list doesn't run until a response is received.

Try creating another function to display your alert, and call that from the get's callback:

  jQuery('#country').live("change", function(){ 
    populateCityListBox();
  }); 

function showCity()
{
    alert(jQuery("select#city").val());
}

- - - -  - - - - - - - - - - -

  function populateCityListBox()
  {

    jQuery.get("my/path/myfile.php", { instance: 'getCitiesByCountry', countryID: jQuery("select#country").val(), brandID: $_GET('brandID') },
      function(data)
      {
          var options = '';
          for (var i = 0; i < data.length; i++) {
            if (i == 0)
              options += '<option selected value="' + data[i].city + '">' + data[i].city + '</option>';
            else
              options += '<option value="' + data[i].city + '">' + data[i].city + '</option>';

          }

          jQuery("select#city").append(options);
          showCity();
      },"json");
  }
Nick Riggs
ok, thanks. That actually worked. What I need to do, is to update a google map with "selected" city. replacing showCity() with updateMap() works. But I'm not really comfortable adding it inside the populateCityListBox() - just seems like the wrong place to put it.
Steven
A: 

You are using a AJAX call to populate the city list box. Unless you changed the default, the call is asynchronous; hence, there is no guarantee it completes before alert() is called.

It is better to call alert() in a on-success callback that you pass to get() as a third argument:

jQuery.get(your_url, your_data, function() {alert('...');})
Bart