サジェスト型入力支援
Googleサジェスト風入力支援サンプル。
テキストボックスに入力した文字に応じて、次々と候補の文字列が表示されます
<手順>
(1)onkeyupイベントにより、inputText()関数がコールされる。
(2)inputText()関数では、入力された値をURLエンコードして、XMLHttpRequestのGETデータとする。
(3)サーバ側のPHPプログラムでは、大文字小文字を区別せずに、候補となる国名をカンマ区切りで出力する。
PHPでは、<?php ?>前後の改行や空白なども出力されるため、先頭と末尾にもカンマを加える。
(4)JavaScriptプログラムでは、カンマで分割して各単語を出力する際に、最初と最後の単語を無視して出力する。
Internet Explorerの「オートコンプリート」機能を無効化するために、inputタグ(テキストボックス)で、autocomplete="off"と指定します。
PHPファイル
要素作成
var divElem = document.createElement('div');
// mouseover/mouseoutによるスタイルを設定
divElem.onmouseover = function (){
this.style.backgroundColor = "#AAA";
}
divElem.onmouseout = function (){
this.style.backgroundColor = "#EEE";
}
topElem.appendChild(divElem);
}
}
function selected(str, target_id, result_id){
// テキストボックスに値を入力
document.getElementById(target_id).value = str;
// 出力先のトップ要素となるdiv要素
var topElem = document.getElementById(result_id);
// div要素の子要素クリア
deleteMenu(topElem);
}
// トップ要素の子要素クリア
function deleteMenu(topElem){
var child = topElem.childNodes;
var length = child.length;
for(var i = 0; i < length; i++) {
topElem.removeChild(child[0]);
}
}
HTML
CVSファイル
Afghanistan,Albania,Algeria,American Samoa,Andorra,Angola,Anguill, (略)