ตัวอย่าง autocomplete จากข้อมูลชุดนึงที่เราสร้างขึ้นมา
1.ประกาศข้อมูลในตัวแปรarray
2.ให้ใช้autocomplete กับid="tags"
3.กำหนดที่หาของข้อมูล
4.เอาค่าจากtext fieldมาเก็บในตัวแปร valInput
-minLength: 0, คือ กำหนดความยาวตัวอักษรเพื่อแสดงautocomplete
-open:function(){ คือ เปิดฟังชั่น
-$(".ui-menu-item a").each(function(){ คือ ใช้คลาสui-menu-item a และวนลูปข้อมูลในฟังชั่นก์
-var matcher = new RegExp("("+valInput+")", "ig" ); //เชคค่าที่กรอกจากtextfield กับ จากข้อมูลที่ดึงมาเปรียบเทียบ
-var s=$(this).text(); //เชคค่าที่กรอกจากtextfield กับ จากข้อมูลที่ดึงมาเปรียบเทียบ
-var newText=s.replace(matcher, "<b>$1</b>"); แทนที่อักษรที่ใช้ค้นหาด้วย ตัวหนา
-$(this).html(newText);
5.ถ้าค่าไม่ว่างให้ทำคำสั่งในเงื่อนไข
6.สร้างปุ่มขึ้นมา
-.attr( "tabIndex", -1 ) คือ สร้างtabindex เส้นทางคีบอร์ด
-.attr( "title", "Show All Items" ) คือ เวลานำเมาส์ไว้ตำแหน่งปุ่ม จะแสดงข้อความShow All Items
-.addClass("myselect") คือ ประกาศชื่อclass
.insertAfter("#tags") คือ ให้แท๊กไว้หลังtextfield id="tags"
7.เป็นขั้นตอนการปิดautocomplete
โค้ด: เลือกทั้งหมด
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jquery ui autocomplete</title>
<style type="text/css">
body {
font-family:tahoma, "Microsoft Sans Serif", sans-serif, Verdana;
font-size:12px;
}
</style>
<link type="text/css" rel="stylesheet" href="autocomplete.css" />
<style>
</style>
</head>
<body>
<label for="tags">Tags: </label>
<input id="tags" />
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function () {
var test = ["test","55555","ant","bee","cat","rat","elephant","lion","tiger","cow"]; //1
$( "#tags" ).autocomplete({ //2
minLength: 0,
source: test, //3
open:function(){
var valInput=$(this).val();//4
if(valInput!=""){ //5
$(".ui-menu-item a").each(function(){
var matcher = new RegExp("("+valInput+")", "ig" );
var s=$(this).text();
var newText=s.replace(matcher, "<b>$1</b>");
$(this).html(newText);
});
}
}
});
$( "<button> </button>" )//6
.attr( "tabIndex", -1 )
.attr( "title", "Show All Items" )
.addClass("myselect")
.insertAfter("#tags")
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass( "ui-corner-all" )
.addClass( "ui-corner-right ui-button-icon" )
.click(function() {
if ($( "#tags" ).autocomplete( "widget" ).is( ":visible" )//7 ) {
$( "#tags" ).autocomplete( "close" );
return;
}
$( "#tags" ).autocomplete( "search", "" );
$( "#tags" ).focus();
});
});
</script>
</body>
</html>