1

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

2 Answers 2

1

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
    });
}
Sign up to request clarification or add additional context in comments.

Comments

0

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
      }
    )
  });
}

Comments

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.