Hello, I have this code to print all locations from a json file:

countries.json:

    {
        "af": {
            "name": "Afghanistan",
            "phoneCode": "93"
        },
        "al": {
            "name": "Albania",
            "phoneCode": "355"
        },
        "dz": {
            "name": "Algeria",
            "phoneCode": "213"
        },
        "ad": {
            "name": "Andorra",
            "phoneCode": "376"
        }

 }

Jquery:

    function getData() {
            $.ajax({
                url: "countries.json",
                success: function (data) {
                    var json = $.parseJSON(data);
                    var output = '<ul>';
                    $.each(json, function(i,v)
                    {
                        output += '<li>ObjectName: ' + i + ' Country Name: ' + v.name + ' Number: ' + v.phoneCode + '</li>';
                    });
                    output += '</ul>';
                    $('#results').html(output);
                }
            });

    }

Please, If I do want to use it a typeahead to change list of cities depending on Country select:

Typeahead one: Input country
Typeahead two: Input states

Html:

Country:
<input type="text" id="list-countries"/>

States:
<input type="text" id="list-states"/>

Pseudocode:

If 'typeahead one' = Canada
                                then 
                                'typeahead two' should list states in Canada: like texas...

Dani AI

Generated

A few practical points to bridge what has posted and a working dependent typeahead:

  • The usual pattern is: load (or fetch) countries and states, build a fast lookup keyed by country code, initialize the country typeahead, then when a country is selected replace or reinitialize the states typeahead with that country’s list. A very common gotcha in your samples is lettercase — your countries keys and the country field in the states file must be normalized (e.g. both toUpperCase()) so the lookup actually matches.

  • Build an index once and reuse it (fast O(1) lookup), then reinit the second typeahead on selection. Example (Typeahead.js + Bloodhound style):

/* assume `countries` = [{name:'Canada',code:'CA'}, ...]
   and `states` = [{country:'CA',name:'Ontario'}, ...] */
var statesIndex = {};
states.forEach(function(s){
  var c = (s.country || '').toUpperCase();
  if (!statesIndex[c]) statesIndex[c] = [];
  statesIndex[c].push(s.name);
});

/* init country typeahead (using Bloodhound) */
var countriesBH = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  local: countries
});
$('#list-countries').typeahead(null, { name:'countries', display:'name', source:countriesBH });

$('#list-countries').on('typeahead:select', function(ev, suggestion){
  var code = (suggestion.code || '').toUpperCase();
  var list = statesIndex[code] || [];
  $('#list-states').typeahead('destroy'); // clear old dataset
  $('#list-states').typeahead(null, { name:'states', source: function(q, sync){ sync(list); }, display: function(v){return v;} });
  $('#list-states').prop('disabled', list.length === 0).val('');
});
  • Extra tips: disable/clear the states input until a country is chosen; for very large state datasets lazy-load the states for the selected country (use $.getJSON with a country param); keep the visible label (country/state name) separate from the stored value (country code) so form submissions remain reliable. These small steps fix the mismatch issues and make the dependent typeahead responsive and robust.

I forgot to add the Json file for states:

json:

{
    "states":[  {"country":"AD","type":"AIRP","Coord":"42.5,1.51666666666667","name":"Andorra la Vella"},   {"country":"AE","type":"PRT","Coord":"25.4833333333333,53.1333333333333","name":"Abu al Bukhoosh"}
    }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.