views:

72

answers:

2

Hi,

i've got a select box containing countries, and when one is selected, i want my autocomplete data for the city field to load via ajax.

here's my code:

// Sets up the autocompleter depending on the currently
// selected country
$(document).ready(function() {
  var cache = getCities();
  $('#registration_city_id').autocomplete(
    {
      source: cache               
    }
  );

  cache = getCities();

  // update the cache array when a different country is selected
  $("#registration_country_id").change(function() {
    cache = getCities();
  });
});

/**
 * Gets the cities associated with the currently selected country
 */
function getCities()
{
  var cityId = $("#registration_country_id :selected").attr('value');
  return $.getJSON("/ajax/cities/" + cityId + ".html");
}

This returns the following json: ["Aberdare","Aberdeen","Aberystwyth","Abingdon","Accrington","Airdrie","Aldershot","Alfreton","Alloa","Altrincham","Amersham","Andover","Antrim","Arbroath","Ardrossan","Arnold","Ashford","Ashington","Ashton-under-Lyne","Atherton","Aylesbury","Ayr",... ]

But, it doesn't work. When i start typing in the city box, the style changes so the autocompleter is doing something, but it won't display this data. If i hard-code the above it works.

Can anyone see what's wrong?

Thanks

+1  A: 

I think you have to use a callback method for your asynchronous call to get the remote JSON data (See Ajax/jQuery.getJSON). Maybe you can store the cities in a global variable or set the response directly as source of your autocomplete control:

function updateCities()
{
    var cityId = $("#registration_country_id :selected").attr('value');
    $.getJSON("/ajax/cities/" + cityId + ".html", function(json){
       CITY_CACHE = json;
       //Alternatively set the source of the autocomplete control
    });
}
aeby
A: 

Thanks, but the answer was:

// Sets up the autocompleter depending on the currently
// selected country
$(document).ready(function() {

  setupAutocompleter();

  // update the cache array when a different country is selected
  $("#registration_country_id").change(function() {
    setupAutocompleter();
  });
});

function setupAutocompleter()
{
  var cityId = $("#registration_country_id :selected").attr('value');
  $.getJSON("/ajax/cities/" + cityId + ".html", function(cities) {
    $('#registration_city_id').autocomplete(
      {
        source: cities
      }
    )
  });
}
Roger