タイトルとは異なる値でオートコンプリート
-
03-07-2019 - |
質問
jqueryを使用してオートコンプリートフォームを作成しようとしていますが、問題が発生しました。ユーザーがデータベースにある場所の名前を入力し始めると、オートコンプリートの場所のフルネームが表示されるようにしようとしていますが、クリックするとテキストボックスがいっぱいになりますGoogleマップで見つけることができる場所の住所。これを達成する最良の方法は何ですか?
解決
ここで、開始するためのコードの非常に大まかなスケッチを示します。決して完全ではありませんが、良い出発点を与えるはずです。役に立てば幸いです
$("#mySearchBox").change(function(){
/*
send a ajax request to receive a json object.
We use the callback function to populate the
a div tag "autocomplete" with the names
*/
$.getJSON("http://myurl.com/myPage?search="+$(this).val()
function(data){
$.each(data.items, function(i,item){
/*
Assume item looks like this
item = {[{"address": 100 Main st",
"name": "Bob and Joe's Dinner"],
...
}
*/
/* Populate autocomplete with new spans
We use the text attribute to hold the address
You may want to look in to jquery data() feature.
*/
$("#autoComplete").append('<span text="'+ item.address +
'" class="searchResult">'+ item.name +'</span>');
});
});
});
$("#autoComplete .searchResults").click(function(){
/*
Here we handle what the user clicks on.
Pull out the address from the attr and
put that back in the mySearchBox
*/
var address = $(this).attr("text");
//Load the adress back int the textfield
$("#mySearchBox").val = address;
});
他のヒント
おそらく「Person」全体を渡すJSONオブジェクトを使用してオブジェクトをJavaScriptに変換します。次に、オブジェクトの各部分をどこに配置するかを選択できます。
所属していません StackOverflow