2017-08-10 9 views
2

私はjsonという名前のnames.jsonを持っています.Json内で 'name'値を探すオートコンプリートで入力する必要があります。jQueryオートコンプリートwith getJSON

どうすればよいですか?

私が試した:

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

をしかし、私は私のコードで間違った何かをやっています。

私はJSONはまさにこの形式から、私は入力に入力すると「名前」の値を返す必要がされている外部ファイルから

をJSONを取得する:ここで

[ 
    { 
     "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 
     } 
    ] 

答えて

1

あなたが与えたデータに基づいて、基本的な作業のオートコンプリートの例です。

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

はまたjsFiddle

上でホストされている上記のコードの作業バージョンです外部ソース、ここで私はそれを行う方法です

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

jsFiddle

+0

上でそれを試してみてくださいあなたが@dawitありがとう!!そして、私はどのように外部URLからjsonを取得するのですか? $ .getJSON? – CodeG

+0

@CodeG新しいアップデートをチェックアウトします。あなたに懸念がある場合は私に知らせてください – dawit