CodeG
CodeG

Reputation: 467

jQuery autocomplete with getJSON

I have a json named names.json and I need to do an input with autocomplete that looks for 'name' values inside the json.

How do I do that?

I Tried:

$(function () {
    var getData = function (request, response) {
   $.getJSON(
       "/cities.json" + request.term,
       function (data) {
           response(data);
       });
    };

    var selectItem = function (event, ui) {
        $("#myInput").val(ui.item.value);
        return false;
    }

    $("#myInput").autocomplete({
        source: getData,
        select: selectItem,
        minLength: 2,
        change: function() {
            $("#myInput").val("").css("display", 2);
        }
    });
});

But I'm doing something wrong in my code.

I get a json from an external file

JSON is exactly from this format, I need to return the values of 'names' when I type in the input:

[  
   {  
      "id":25,
      "name":"locale name test 2",
      "state_id":6
   },
   {  
      "id":667,
      "name":"locale name test 3",
      "state_id":24
   },
   {  
      "id":331,
      "name":"locale name test 4",
      "state_id":13
       },
       {  
          "id":776,
          "name":"locale name test 5",
          "state_id":26
       },
       {  
          "id":680,
          "name":"locale name test 6",
          "state_id":26
       }
    ]

Upvotes: 2

Views: 3138

Answers (1)

user8233884
user8233884

Reputation:

Here is base working autocomplete example based on the data you gave.

HTML:

<input type="text" id="suggestion" />

Jquery:

var data = [  
   {  
      "id":25,
      "name":"locale name test 2",
      "state_id":6
   },
   {  
      "id":667,
      "name":"locale name test 3",
      "state_id":24
   },
   {  
      "id":331,
      "name":"locale name test 4",
      "state_id":13
       },
       {  
          "id":776,
          "name":"locale name test 5",
          "state_id":26
       },
       {  
          "id":680,
          "name":"locale name test 6",
          "state_id":26
       }
    ]

 var data_arr = data.map(function(val){
     return val.name;
 }). //get all the val.names on an array to make 
    // it easier when it comes setting autocomplete source
 console.log(data_arr)

$("#suggestion").autocomplete({
    source: data_arr,
    minLength: 2
});

Here is the working version of the above code hosted on jsFiddle

In addition: if you have to get the data from external source, here is how I would do it

HTML:

<input type="text" id="suggestion" />

Jquery:

// I have hosted the same data you provided on myjson.com

 $.getJSON( "https://api.myjson.com/bins/1gkh25", function( data ) {

  var data_arr = data.map(function(val){
             return val.name;
    })

   auto(data_arr)

  });

function auto(data_arr){

   $("#suggestion").autocomplete({
        source: data_arr,
        minLength: 2
    });
}

try it on jsFiddle

Upvotes: 2

Related Questions