Adarsh Nair
Adarsh Nair

Reputation: 390

Autocompleting the Json

I have a Json data of countries and cities in it. I wanted to know how to parse this data in order to get a autocomplete input box in HTML which shows cities in the JSON starting from the substring entered using jQuery. I am using jquery-ui for this. The problem I am facing is the way in which json is stored. No key values are given as all the names under country are cities. I am not able to use jquery-ui.js https://gist.githubusercontent.com/mayurah/5f4a6b18b1aa8c26910f/raw/countriesToCities.json The code I have got is this:

  $(function() {
   function log( message ) {
     $( "<div>" ).text( message ).prependTo( "#log" );
     $( "#log" ).scrollTop( 0 );
   }

  $( "#location" ).autocomplete({
   source: function( request, response ) {
    $.ajax({
      url: "https://gist.githubusercontent.com/mayurah/5f4a6b18b1aa8c26910f/raw/countriesToCities.json",
      dataType: "json",
      data: {
        q: request.item
      },
      success: function( data ) {
        response( data );
      }
     });
   },
   minLength: 3,
   select: function( event, ui ) {
    log( ui.item ?
      "Selected: " + ui.item.label :
      "Nothing selected, input was " + this.value);
   },
   open: function() {
    $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
   },
   close: function() {
    $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
   }
  });    
 });    

Upvotes: 0

Views: 90

Answers (1)

Trace
Trace

Reputation: 18859

Are you looking for something like this:

response( 
    $.map(data, function (list) { 
        $.map(list, function(city) {
            return { label: city }; 
        }); 
    })); 

Upvotes: 1

Related Questions