まず以下を読み込む
<link type="text/css" rel="stylesheet"
href="http://code.jquery.com/ui/1.10.3/themes/cupertino/jquery-ui.min.css" />
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript"
src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js"></script>
サンプルコード
autocomplete.js
$(function(){
/** プロジェクト名が変更になっても修正が必要なくなるよう実装**/
var pathname = location.pathname.split("/")[1];
$.ajax({
/** オートコンプリート用のリストを取得するURL*/
url: "/" + pathname + "/getAutoComplete",
dataType: "json",
type: 'GET'
}).then(function(searchResult){ /** 検索結果のリストは引数に自動で入る*/
$('.txtKeywd').autocomplete({ /** 実装したい入力欄のid/classを指定*/
source : searchResult, /** 候補リスト(必須)*/
autoFocus: true, /**リスト表示に際してリスト先頭にフォーカスするか*/
delay: 500, /**キー入力からリスト表示までの遅延時間(ミリ秒)*/
minLength: 1 /**オートコンプリート機能が働く最小文字数*/
});
},function(){
});
});
GetAutoCompleteController.java
import net.arnx.jsonic.JSON;
/** 商品検索フォームのオートコンプリート用コントローラ. */
@Controller
@RequestMapping("/getAutoComplete")
public class GetAutoCompleteController {
/** 全商品名をオートコンプリートに渡す. */
@ResponseBody
@RequestMapping
public String getAutoComplete(){
List<String> nameList = getAutoCompleteService.getAllNameList();
return JSON.encode(nameList);
}
}
注意点
JSONのエンコーダはJSONICを使用していますので、dependencyタグはコチラから入手してpom.xmlに追加
https://mvnrepository.com/artifact/net.arnx/jsonicJSON.encode()に何を渡すか
ドメイン:オブジェクトを渡すとフィールド名をキーとするマップ(連想配列)をjsのsarchResultに渡す)
リストオブジェクト:リストをそのままjsのsarchResultに渡す)
参考
AutocompleteをjQueryのAutocomponentで実現
http://qiita.com/yu_0105/items/20c4f52e71020af42e7bJQUERY オートコンプリート・入力補完インタフェースまとめ
http://blog.lowaivill.com/ui/jquery-autocomplete/
autoFocus: 候補メニューの最初の候補に自動フォーカス
delay: 入力されて検索実行までのディレイ時間
minLength: 候補表示するための最低の入力文字数
その他のオプションについては、以下を参考。
Autocomplete Widget | jQuery UI API Documentation