0

I am using jquery auto complete to populate city names when user starts writing. These cities are from multiple countries and what I want to do now is to populate relevant cities if the user types in country name.

So for example if the user types in 'San' jquery will populate the auto complete with ['San Diego','Santiago']. Now if the user types in United States I want the auto complete to be populated with ['New York City', 'Boston', 'Seattle', 'San Diego', etc..].

What I can do is to create HashMap with country as key and list of cities as value. Then I can just change the source of the auto complete appropriately whenever the input matches a country name.

$( "#citySearch" ).autocomplete({source: citySearchList});

Now the problem is displaying all options in the source even if United States will not trigger ['New York', 'Boston', etc..] in the normal implementation of autocomplete.

I tried using the trick in this answer

Community
  • 1
  • 1
Mazvél
  • 951
  • 1
  • 8
  • 22
  • 1
    The results of the `ajax` request are something you'd get from the server, nothing to do with autocomplete or JavaScript at all. In other words, your server-side code and SQL query is where you'd focus your efforts. – Sparky Mar 18 '15 at 14:56
  • where do you have the `city` and `county` data stored? – Jordi Castilla Mar 18 '15 at 14:57
  • @JordiCastilla I am getting `cities` through `JSON` and simply using `$( "#citySearch" ).autocomplete({source: citySearchList});` I guess the best solution is to check if the input in the `#citySearch` matches any `country` and populate with relevcant cities. – Mazvél Mar 18 '15 at 15:16
  • how you know relation btw `city-country`? – Jordi Castilla Mar 18 '15 at 15:47
  • I will load them over `JSON` and probably create the javascript equivalent of `hashmap` to store them. – Mazvél Mar 18 '15 at 15:59

1 Answers1

1

If the search input contains a name of a country you can get a list of cities from that country and do something like this:

$( "#citySearch" ).autocomplete({ source: citySearchList, minLength :0 });
$( "#citySearch" ).autocomplete("search", "");

When the input is not a country name in your data, you simply change the source back to the original data.

Setting minLength to 0 and then use the search method to search for "" will display all the data in the autocomplete source array.