Jquery simulated search box automatically completes the Search Prompt function (improved)

Source: Internet
Author: User
Tags autopoint

Autopoint. js code: Copy codeThe Code is as follows :/*
* @ Date: 21:42:15
* @ Author: Hu lingwei
* Depends:
* Jquery. js
*
* Function: similar to the GOOGLE search box prompt function
*/
(Function ($ ){
$. Fn. autopoint = function (options ){
Defaults = {
Url: options. url,
KeyLeft: 37, // left direction key
KeyUp: 38, // up arrow key
KeyRight: 39, // right direction key
KeyDown: 40, // downward direction key
KeyEnter: 13, // enter key
ListHoverCSS: 'jhover ', // a list of mouse hover styles in the prompt box
Tpl: '<div class = "list"> <div class = "word"> {word} </div> <div class = "view"> about {view} records </ div> </div> ',
Topoffset: options. topoffset | 5
};
Var options = $. extend (defaults, options );
Var dropDiv = $ ('<div> </div>'). addClass ('dropdiv '). appendTo ('body ');
Var isOver = false;
DropDiv. hover (function (){
IsOver = true;
}, Function (){
IsOver = false;
});
Return this. each (function (){
Var pa = $ (this );
$ (This). bind ('keylow', function (event ){
If (dropDiv.css ('display ')! = 'None') {// handle keyboard events only when the prompt layer is displayed.
Var currentList = dropDiv. find ('.' + options. listHoverCSS );
If (event. keyCode = options. keyDown) {// if you press the downward arrow key
If (currentList. length = 0 ){
// If no one in the prompt list is selected, select the first one in the list.
$ (This). val (getPointWord (dropDiv. find ('. list: first ')
. Mouseover ()));
} Else if (currentList. next (). length = 0 ){
// If the last one is selected, it is unselected and the input box is selected.
UnHoverAll ();
} Else {
UnHoverAll ();
// Select the next column of the selected column
If (currentList. next (). length! = 0)
$ (This). val (getPointWord (currentList. next ()
. Mouseover ()));
}
Return false;
} Else if (event. keyCode = options. keyUp) {// if you press the up arrow key
If (currentList. length = 0 ){
$ (This). val (getPointWord (dropDiv. find ('. list: la ')
. Mouseover ()));
} Else if (currentList. prev (). length = 0 ){
UnHoverAll ();
} Else {
UnHoverAll ();
If (currentList. prev (). length! = 0)
$ (This). val (getPointWord (currentList. prev ()
. Mouseover ()));
}
Return false;
} Else if (event. keyCode = options. keyEnter) dropDiv. empty (). hide ();
}
// Record the value of the input box before pressing the key to check whether the value of the key has changed.
$ (This). attr ('alt', $ (this). val ());
}). Bind ('keyup', function (event ){
// If the highlighted key is the up or down direction key, return
If (event. keyCode = options. keyDown | event. keyCode = options. keyUp) return;
If ($ (this). val () = ''){
DropDiv. empty (). hide ();
Return;
}
// If the value of the input box is not changed or becomes null, return
If ($ (this). val () ==$ (this). attr ('alt '))
Return;
GetData (pa, $ (this). val ());
}). Bind ('blur', function (){
If (isOver & dropDiv. find ('.' + options. listHoverCSS )! = 0) return;
// If the text input box loses focus, it is cleared and the prompt layer is hidden.
DropDiv. empty (). hide ();
});
/** Method for processing ajax return success **/
HandleResponse = function (parent, json ){
Var isEmpty = true;
For (var o in json ){
If (o = 'data') isEmpty = false;
}
If (isEmpty ){
ShowError ("returned data format error. Please check whether the request URL is correct! ");
Return;
}
If (json ['data']. length = 0 ){
// The returned data is empty.
Return;
}
RefreshDropDiv (parent, json );
DropDiv. show ();
}
/** Method for processing ajax failures **/
HandleError = function (error ){
// ShowError ("failed due to url error or timeout request! ");
}
ShowError = function (error ){
Alert (error );
}
/** Use ajax to return json format data to generate a dom string **/
Render = function (parent, json ){
Var res = json ['data'] | json;
Var appendStr = '';
// Replace the matching/\ {([a-z] +) \}/ig content in the template string with the content in the json object, for example, {word}, {view}
For (var I = 0; I <res. length; I + = 1 ){
AppendStr + = options. tpl. replace (/\ {([a-z] +) \}/ig, function (m, n ){
Return res [I] [n];
});
}
Jebind (parent, appendStr );
}
/** Insert the new dom object to the prompt box and re-bind the mouseover event listener **/
Jebind = function (parent, ){
DropDiv. append ();
DropDiv. find ('. list'). each (function (){
$ (This). unbind ('mouseover'). mouseover (function (){
UnHoverAll ();
$ (This). addClass (options. listHoverCSS );
}). Unbind ('click'). click (function (){
Parent. val (getPointWord ($ (this )));
DropDiv. empty (). hide ();
Parent. focus ();
});
});
}
/** Remove the hover style of all columns in the prompt box **/
UnHoverAll = function (){
DropDiv. find ('. list'). each (function (){
$ (This). removeClass (options. listHoverCSS );
});
}
/** Get the currently selected prompt keyword in the prompt box **/
GetPointWord = function (p ){
Return p. find ('div: first '). text ()
}
/** Refresh the prompt box and set the style **/
RefreshDropDiv = function (parent, json ){
Var left = parent. offset (). left;
Var height = parent. height ();
Var top = parent. offset (). top + options. topoffset + height;
Var width = options. width | parent. width () + 'px ';
DropDiv. empty ();
DropDiv.css ({
'Border': '1px solid # FE00DF ',
'Left': left,
'Top': top,
'Width': width
});
Render (parent, json );
// Prevent the prompt box from disappearing because the focus of the input box is lost before ajax returns
Parent. focus ();
}
/** Request data from the server through ajax **/
GetData = function (parent, word ){
$. Ajax ({
Type: 'get ',
Data: "word =" + word,
Url: options. url,
DataType: 'json ',
Timeout: 1000,
Success: function (json) {handleResponse (parent, json );},
Error: handleError
});
}
});
}
}) (JQuery );

Main webpage style:Copy codeThe Code is as follows: <style type = "text/css">
. DropDiv {
Position: absolute;
Z-index: 10;
Display: none;
Cursor: hand;
}
. DropDiv. jhover {
Background-color: #00 FEDF;
}
. DropDiv. list {
Float: left;
Width: 100%;
}
. DropDiv. word {
Float: left;
}
. DropDiv. view {
Float: right;
Color: gray;
Text-align: right;
Font-size: 10pt;
}
</Style>

Call method:Copy codeThe Code is as follows: <script type = "text/javascript" src = "../js/jquery-1.4.2.min.js"> </script>
<Script type = "text/javascript" src = ".../js/autopoint-1.0.1.js"> </script>
<Script type = "text/javascript">
$ (Function (){
$ ("Input"). autopoint ({url: 'http: // localhost/xun/ajax. svl? Method = getsearchhelp '});
});
</Script>
<Body>
<Input type = "text" size = "50"/>
<Input type = "text" size = "50"/>
</Body>

Servlet main part:Copy codeThe Code is as follows: response. setContentType ("text/html ");
Response. setHeader ("Cache-Control", "no-cache ");
Response. setCharacterEncoding ("UTF-8 ");
String word = request. getParameter ("word ");
If (Utils. isBlank (word) return;
JSONObject json = new JSONObject ();
JSONArray array = new JSONArray ();
Map <String, Object> map1 = new HashMap <String, Object> ();
Map1.put ("word", word + "a1 ");
Map1.put ("view", 10 );
Map <String, Object> map2 = new HashMap <String, Object> ();
Map2.put ("word", word + "a2 ");
Map2.put ("view", 15 );
Map <String, Object> map3 = new HashMap <String, Object> ();
Map3.put ("word", word + "a3 ");
Map3.put ("view", 2 );
Array. add (JSONObject. fromObject (map1 ));
Array. add (JSONObject. fromObject (map2 ));
Array. add (JSONObject. fromObject (map3 ));
Json. put ("data", array );
PrintWriter out = response. getWriter ();
Out. print (json. toString ());
Out. close ();

Among them, JSONObject and JSONArray class from the json-lib.jar, for the convenience of testing, is directly returned data, can be replaced
Query data from the data source.

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.