2009年7月25日土曜日

SuggestをjQueryで作ってみた

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title></title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1");
google.setOnLoadCallback(function(){
var arr = ["abc","abf","abo","b4","bce","日本語","日本","アメリカ","アフリカ","どいつ"];
var dft = -1:
$("#txt").keyup(function(e){
if(e.keyCode == 40){//下
if(dft == -1){
dft++;
$("p").eq(dft).css({backgroundColor: "#e8eefa"});
return;
}
else if(dft > -1){
var len = $("p").length;
if(dft == len)
return false;

$("p").eq(dft).css({backgroundColor: "white"});

dft++;
$("p").eq(dft).css({backgroundColor: "#e8eefa"});
return;
}
}
else if(e.keyCode == 38){//上
if(dft == 0){
$("p").eq(dft).css({backgroundColor: "white"});
dft = -1;
return;
}
else if(dft > 0){
$("p").eq(dft).css({backgroundColor: "white"});
dft = dft - 1;
$("p").eq(dft).css({backgroundColor: "#e8eefa"});
return;
}
}
else if(e.keyCode == 13){
var tex = $("p").eq(dft).text();
$("#txt").val(tex);
}
var a = $("#txt").val();
var c = "";
if (a != ""){
var bol = false;
jQuery.each(arr,function(){
if (this.indexOf(a) > -1 ){
c = "<p>"+this+"</p>" + c;
bol = true;
}//if
});//each
if(bol){
$("div").empty();
$("div").append(c);
dft = -1;
$("p").css({backgroundColor: "white"});
$("div").css({visibility: "visible"});
}
}//if
if(a == ""){
$("div").empty();
$("div").css({visibility: "hidden"});
}
});//keyup

$("#btn").click(function(){
alert(dft);
});

$("p").click(function(){
alert("a");
});
});

</script>

<style type="text/css">
div
{
width: 170px;
border-left: solid #c3d9ff 1px;
border-right: solid #c3d9ff 1px;
visibility: visible;
}
hr
{
color: #c3d9ff;
}

p
{
height: 12px;
padding-bottom: 2px;
padding-left: 2px;
font-size: 10px;
border-bottom: solid black 1px;
}
</style>
</head>
<body>
<input type="text" id="txt"/><input type="button" id="sbt" value=" send "/><br>
<div>
</div>
<input type="button" id="btn" value=" exe "/>
</body>
</html>


googleのサジェストではタイマーを使うことで確定前の文字も取得できるようにしているらしい。機会があれば同じようなのを作ってみたい。

0 件のコメント:

コメントを投稿