Based on jquery implementation of similar Baidu search input box autocomplete function _jquery

Source: Internet
Author: User
Nonsense not much said, intuitive look at:

Implementing this feature requires service-side coordination. The client uses a script to show the data obtained from the server.

Look at the client's HTML first:

Copy Code code as follows:

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 strict//en"
"Http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" >
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
<title> search terms automatically completed </title>
<style type= "Text/css" >
#search {
Text-align:center;
position:relative;
}
. autocomplete{
border:1px solid #9ACCFB;
Background-color:white;
Text-align:left;
}
. AutoComplete li{
List-style-type:none;
}
. clickable {
Cursor:default;
}
. Highlight {
Background-color: #9ACCFB;
}
</style>
<script type= "Text/javascript" src= "Jquery.js" ></script>
<script type= "Text/javascript" >
$ (function () {
Get div Layer
var $search = $ (' #search ');
Get the input box jquery object
var $searchInput = $search. Find (' #search-text ');
Turn off the automatic completion of the browser provided to the input box
$searchInput. attr (' AutoComplete ', ' off ');
Create an auto-complete drop-down list to display the data returned by the server, insert it behind the search button, and then adjust the position when displayed.
var $autocomplete = $ (' <div class= "autocomplete" ></div> ")
. Hide ()
. InsertAfter (' #submit ');
Empty the contents of the Drop-down list and hide the Drop-down list area
var clear = function () {
$autocomplete. Empty (). Hide ();
};
Registers an event, empties the Drop-down list and hides when the input box loses focus
$searchInput. blur (function () {
SetTimeout (clear,500);
});
The index of the highlighted item in the Drop-down list, when the Drop-down list item is displayed, moving the mouse or keyboard keys will move the highlighted items, like Baidu Search
var selecteditem = null;
ID of the timeout
var timeoutid = null;
Set the highlight background of a Drop-down item
var Setselecteditem = function (item) {
Update index variables
SelectedItem = Item;
Press the up and down key is the loop display, less than 0 is placed into the maximum value, greater than the maximum is placed into 0
if (SelectedItem < 0) {
SelectedItem = $autocomplete. Find (' Li '). length-1;
}
else if (SelectedItem > $autocomplete. Find (' Li '). length-1) {
SelectedItem = 0;
}
First remove the highlighted background of other list items, and then highlight the background of the current index
$autocomplete. Find (' Li '). Removeclass (' highlight ')
. EQ (SelectedItem). addclass (' highlight ');
};
var ajax_request = function () {
Ajax service-side communication
$.ajax ({
' URL ': '/test/index.jsp ',//address of the server
' Data ': {' search-text ': $searchInput. Val ()},//Parameter
' DataType ': ' json ',//Return data type
' type ': ' POST ',//request type
' Success ': function (data) {
if (data.length) {
Traversing data, adding to the auto completion area
$.each (data, function (index,term) {
Create an Li tag and add it to the Drop-down list
$ (' <li></li> '). Text (term). Appendto ($autocomplete)
. addclass (' clickable ')
. Hover (function () {
Drop-down List of events for each item, mouse move into the operation
$ (this). Siblings (). Removeclass (' highlight ');
$ (this). addclass (' highlight ');
SelectedItem = index;
},function () {
Drop-down List of events for each item, the mouse left the operation
$ (this). Removeclass (' highlight ');
Index-1 when the mouse is left, as a marker
SelectedItem =-1;
})
. Click (function () {
When you click this item in the Drop-down list, you add the value of this item to the input box
$searchInput. Val (term);
Empty and hide the Drop-down list
$autocomplete. Empty (). Hide ();
});
});//Event registration completed
Set the location of the Drop-down list, and then display the Drop-down list
var ypos = $searchInput. Position (). Top;
var xpos = $searchInput. Position (). Left;
$autocomplete. css (' width ', $searchInput. css (' width '));
$autocomplete. css ({' position ': ' relative ', ' left ': xpos + "px", ' top ': Ypos + "px"});
Setselecteditem (0);
Show drop down list
$autocomplete. Show ();
}
}
});
};
Registering an event with an input box
$searchInput
. KeyUp (Function (event) {
Alphanumeric, backspace, space
if (Event.keycode > | | event.keycode = 8 | | Event.keycode ==32) {
First delete the information in the Drop-down list
$autocomplete. Empty (). Hide ();
Cleartimeout (Timeoutid);
Timeoutid = settimeout (ajax_request,100);
}
else if (Event.keycode = 38) {
On
SelectedItem =-1 represents the mouse to leave
if (SelectedItem = = 1) {
Setselecteditem ($autocomplete. Find (' Li '). length-1);
}
else {
Index minus 1
Setselecteditem (selectedItem-1);
}
Event.preventdefault ();
}
else if (Event.keycode = 40) {
Under
SelectedItem =-1 represents the mouse to leave
if (SelectedItem = = 1) {
Setselecteditem (0);
}
else {
Index plus 1
Setselecteditem (SelectedItem + 1);
}
Event.preventdefault ();
}
})
. KeyPress (Function (event) {
Enter key
if (Event.keycode = = 13) {
The list is empty or the mouse left causes no index value currently
if ($autocomplete. Find (' li '). length = = 0 | | selecteditem = = 1) {
Return
}
$searchInput. val ($autocomplete. Find (' li ')-eq (SelectedItem). text ());
$autocomplete. Empty (). Hide ();
Event.preventdefault ();
}
})
. KeyDown (Function (event) {
ESC key
if (Event.keycode = = 27) {
$autocomplete. Empty (). Hide ();
Event.preventdefault ();
}
});
Registers the window size changes the event, adjusts the Drop-down list position
$ (window). Resize (function () {
var ypos = $searchInput. Position (). Top;
var xpos = $searchInput. Position (). Left;
$autocomplete. css (' width ', $searchInput. css (' width '));
$autocomplete. css ({' position ': ' relative ', ' left ': xpos + "px", ' top ': Ypos + "px"});
});
});
</script>
<body>
<div id = "Search" >
<label for= "Search-text" > Please input keyword </label><input type= "text" id= "Search-text" name= "Search-text"/>
<input type= "button" id= "Submit" value= "Search"/>
</div>
</body>

Server-side code, we choose JSP here, you can also use PHP, the server does not matter, the key is to transmit data.
Copy Code code as follows:

<%@ page language= "java" import= "java.util.*" pageencoding= "Utf-8"%>
<%
String []words = {"Amani", "abc", "Apple", "abstract", "an", "Bike", "Byebye",
"Beat", "Be", "Bing", "Come", "Cup", "Class", "Calendar", "a";
if (Request.getparameter ("Search-text")!= null) {
String key = Request.getparameter ("Search-text");
if (key.length ()!= 0) {
String json= "[";
for (int i = 0; i < words.length; i++) {
if (Words[i].startswith (key)) {
JSON + + "" + words[i] + "\" + ",";
}
}
JSON = json.substring (0,json.length () -1>0?json.length () -1:1);
JSON + = "]";
System.out.println ("JSON:" + JSON);
OUT.PRINTLN (JSON);
}
}
%>

The whole process of thinking is quite clear, first register the KeyUp event on the input box, and then get the JSON object via Ajax in the event. After getting the data, each data creates an Li tag and registers the Click event on the label so that when we click on each item, we can respond to the event. The key to keyboard navigation is to record the currently highlighted index value and adjust the background highlighting based on the index value. The location of the Drop-down list is displayed based on the position of the input box and adjusts the position of the Drop-down list whenever the size of the browser changes.
jquery is the front end of the Web tool, if you have the opportunity, we must see.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.