Jquery-based Automatic completion of input boxes similar to Baidu search

Source: Internet
Author: User

Let's take a look:

To implement this function, the server must cooperate. The client uses a script to display the data obtained from the server.

First look at the client's HTML:
Copy codeThe Code is as follows:
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Strict // EN"
Http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd>
<Html xmlns = "http://www.w3.org/1999/xhtml" xml: lang = "en" lang = "en">
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
<Title> search term automatically completed </title>
<Style type = "text/css">
# Search {
Text-align: center;
Position: relative;
}
. Autocomplete {
Border: 1px solid #9 ACCFB;
Background-color: white;
Text-align: left;
}
. Autocomplete li {
List-style-type: none;
}
. Clickable {
Cursor: default;
}
. Highlight {
Background-color: #9 ACCFB;
}
</Style>
<Script type = "text/javascript" src = "jquery. js"> </script>
<Script type = "text/javascript">
$ (Function (){
// Obtain the div Layer
Var $ search =$ ('# search ');
// Obtain the JQuery object in the input box
Var $ searchInput = $ search. find ('# search-text ');
// Close the browser to automatically complete the input box
$ SearchInput. attr ('autocomplete', 'off ');
// Create an automatically completed drop-down list to display the data returned by the server, insert it behind the search button, and adjust the position when displaying it.
Var $ autocomplete = $ ('<div class = "autocomplete"> </div> ')
. Hide ()
. InsertAfter ('# submit ');
// Clear the content of the drop-down list and hide the drop-down list Area
Var clear = function (){
$ Autocomplete. empty (). hide ();
};
// Register the event. When the input box loses focus, clear the drop-down list and hide it.
$ 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, move the mouse or the up or down key on the keyboard to move the highlighted item.
Var selectedItem = null;
// Timeout ID
Var timeoutid = null;
// Set the highlighted background of the drop-down list
Var setSelectedItem = function (item ){
// Update the index variable
SelectedItem = item;
// Press the up and down keys to display them cyclically. If the value is smaller than 0, it is set to the maximum value. If the value is greater than the maximum value, it is set to 0.
If (selectedItem <0 ){
SelectedItem = $ autocomplete. find ('lil'). length-1;
}
Else if (selectedItem> $ autocomplete. find ('lil'). length-1 ){
SelectedItem = 0;
}
// Remove the highlighted background of other list items and then highlight the background of the current index.
$ Autocomplete. find ('lil'). removeClass ('highlight ')
. Eq (selectedItem). addClass ('highlight ');
};
Var ajax_request = function (){
// Ajax Server Communication
$. Ajax ({
'Url': '/test/index. jsp', // server address
'Data': {'search-text': $ searchInput. val ()}, // Parameter
'Ype ype ': 'json', // return data type
'Type': 'post', // request type
'Success': function (data ){
If (data. length ){
// Traverse data and add it to the auto-completion Zone
$. Each (data, function (index, term ){
// Create a li tag and add it to the drop-down list
$ ('<Li> </li>'). text (term). appendTo ($ autocomplete)
. AddClass ('clickable ')
. Hover (function (){
// The Action for moving the cursor to the event of each item in the drop-down list
$ (This). siblings (). removeClass ('highlight ');
$ (This). addClass ('highlight ');
SelectedItem = index;
}, Function (){
// Drop-down list of each item event and move the cursor away
$ (This). removeClass ('highlight ');
// When the mouse leaves, the index is set to-1 as a marker.
SelectedItem =-1;
})
. Click (function (){
// If you click this item in the drop-down list, add the value to the input box.
$ SearchInput. val (term );
// Clear and hide the drop-down list
$ Autocomplete. empty (). hide ();
});
}); // Event registration is complete
// Set the position of the drop-down list and display the drop-down list
Var ypos = $ searchInput. position (). top;
Var xpos = $ searchInput. position (). left;
Using autocomplete.css('width', using searchinput.css ('width '));
Using autocomplete.css ({'position': 'relative ', 'left': xpos + "px", 'top': ypos + "px "});
SetSelectedItem (0 );
// Display the drop-down list
$ Autocomplete. show ();
}
}
});
};
// Register the event in the input box
$ SearchInput
. Keyup (function (event ){
// Letter/number, unsigned, space
If (event. keyCode> 40 | event. keyCode = 8 | event. keyCode = 32 ){
// Delete the information from the drop-down list first
$ Autocomplete. empty (). hide ();
ClearTimeout (timeoutid );
Timeoutid = setTimeout (ajax_request, 100 );
}
Else if (event. keyCode = 38 ){
// Upload
// SelectedItem =-1 indicates that the mouse leaves
If (selectedItem =-1 ){
SetSelectedItem ($ autocomplete. find ('lil'). length-1 );
}
Else {
// Index minus 1
SetSelectedItem (selectedItem-1 );
}
Event. preventDefault ();
}
Else if (event. keyCode = 40 ){
// Lower
// SelectedItem =-1 indicates that the mouse leaves
If (selectedItem =-1 ){
SetSelectedItem (0 );
}
Else {
// Add 1 to the index
SetSelectedItem (selectedItem + 1 );
}
Event. preventDefault ();
}
})
. Keypress (function (event ){
// Enter
If (event. keyCode = 13 ){
// The list is empty or the cursor leaves, causing no index value currently
If ($ autocomplete. find ('lil'). length = 0 | selectedItem =-1 ){
Return;
}
$ SearchInput. val ($ autocomplete. find ('lil'). eq (selectedItem). text ());
$ Autocomplete. empty (). hide ();
Event. preventDefault ();
}
})
. Keydown (function (event ){
// Esc key
If (event. keyCode = 27 ){
$ Autocomplete. empty (). hide ();
Event. preventDefault ();
}
});
// Register the event of window size change and re-adjust the position of the drop-down list
$ (Window). resize (function (){
Var ypos = $ searchInput. position (). top;
Var xpos = $ searchInput. position (). left;
Using autocomplete.css('width', using searchinput.css ('width '));
Using autocomplete.css ({'position': 'relative ', 'left': xpos + "px", 'top': ypos + "px "});
});
});
</Script>
</Head>
<Body>
<Div id = "search">
<Label for = "search-text"> enter keywords </label> <input type = "text" id = "search-text" name = "search-text"/>
<Input type = "button" id = "submit" value = "Search"/>
</Div>
</Body>
</Html>

The server code. We can use JSP or PHP here. The server doesn't matter. The key is to transmit data.
Copy codeThe Code is 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", "china "};
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 entire process is actually quite clear. First, register the keyup event in the input box, and then obtain the json object through ajax in the event. After obtaining the data, create a li tag for each item of data and register the click event on the tag, so that when we click each item, we can respond to the event. The key to keyboard navigation is to record the current highlighted index value and adjust the background highlighted Based on the index value. The position of the displayed drop-down list must be set based on the position of the input box. When the browser size changes, the position of the drop-down list can be adjusted at any time.
JQuery is a powerful web Front-End Tool. If you have the opportunity, you must take a look.

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.