入力フォームに入力補完機能を実装する

入力フォームに入力補完機能を実装する

入力フォームにgoogleの検索フォームのような入力補完機能を実装する。
サンプルページ


jQueryのAutocompleteプラグインを使用すると簡単に実装できる。(下記2つのファイル)
http://view.jquery.com/trunk/plugins/autocomplete/jquery.autocomplete.css
http://view.jquery.com/trunk/plugins/autocomplete/jquery.autocomplete.js


jQuery本体はGoogleホスティングされているものを使用。
http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js

ファイル構成

index.html
jquery.autocomplete.css
jquery.autocomplete.js
suggest.php

index.html
<!DOCTYPE html>

<html lang="ja">
  <head>
    <title>入力補完サンプル</title>
    <meta charset="UTF-8">

    <script type="text/javascript" src= "http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
    <script type="text/javascript" src= "jquery.autocomplete.js"></script>
    <link   type="text/css"        href="jquery.autocomplete.css" media="all" rel="stylesheet" />

    <script type="text/javascript">
       $(document).ready(function(){
         $('#in_text').autocomplete('suggest.php').result(
	  	function(event, item) {
        	item[0];
      	   }
	  );
       });
    </script>
 </head>
 <body>

        <input type="text" size="30" name="in_text" id="in_text"/>

 </body>
</html>

autocomplete('suggest.php')に予測変換候補のリストを出力するスクリプトを指定。
今回はphpで実装。

suggest.php

jQuery Autocompleteには予測変換候補のリストを改行区切りで渡せばよい。
suggest.phpにその機能を実装する。
予測変換候補のリスト取得元はGoogle Suggest APIを使用する。

<?php

require_once("HTTP/Request.php");
$http_request = new HTTP_Request();

//パラメータにds=ytを追加するとYouTubeの予測変換候補のリストが取得できる
$http_request->setURL("http://suggestqueries.google.com/complete/search?hl=ja&client=firefox&json=t&q=".$_GET["q"]);
$http_request->sendRequest();
$result = mb_convert_encoding($http_request->getResponseBody(), "UTF-8", "SJIS");//結果がSJISで戻ってくる。json_decode()へはUTF-8で渡す必要があるため変換。
$result = json_decode($result);

echo implode("\n", $result[1]);
?>