JQuery autocomplate self-extension plug-in, Automatic completion of sample code

Source: Internet
Author: User

Copy codeThe Code is as follows: But it is compatible with browsers. It has been tested to be compatible with IE6 + and Firefox3.5 +.
First take a look At autocomplate. js:
; (Function ($ ){
Var index =-1;
Var timeId;
Var cssOptions = {
"Border": "1px solid black ",
"Background-color": "white ",
"Position": "absolute "/*,
"Font": "normal lighter 14px 6px Times New Roman "*/
};
Var defaults = {
Width: "auto ",
HighlightColor: "# 3399FE ",
UnhighlightColor: "# FFFFFF ",
Css: cssOptions,
DataType: "xml ",
ParamName: "word ",
Delay: 500,
Max: 20
};
Var keys = {
UP: 38,
DOWN: 40,
DEL: 46,
TAB: 9,
ENTER: 13,
ESC: 27,
/* COMMA: 188 ,*/
PAGEUP: 33,
PAGEDOWN: 34,
BACKSPACE: 8,
A: 65,
Z: 90
};
$. Fn. extend ({
Autocomplete: function (sUrl, settings ){
SUrl = (typeof sUrl = "string ")? SUrl :"";
Var param =! This. attr ("id ")? Defaults. paramName: this. attr ("id ");
Settings = $. extend ({}, defaults, {url: sUrl, paramName: param}, settings );
Var autoTip = this. autoTipTemplate (this, settings );
$ ("Body"). append (autoTip );
Var $ this = this;
This. keyup (function (event ){
$ This. keyOperator (event, autoTip, settings );
});
/* $ ("Input [type = button]"). click (function (){
$ ("# Result"). text ("" + search. val () + "in the text box is submitted! ");
$ ("# Auto"). hide ();
Index =-1;
});*/
Return this. each (function (){
$ This. val ();
});
},
AutoTipTemplate: function (input, settings ){
Var inputOffset = input. offset ();
Var autoTip = $ ("<div/>" ).css(settings.css). hide ()
. Css ("top", inputOffset. top + input. height () + 5 + "px ")
. Css ("left", inputOffset. left + "px ");
Var space = $. browser. mozilla? 2: 6; // compatible with browsers
Var tipWidth = (typeof settings. width = "string" & "auto ")? Input. width (): settings. width;
AutoTip. width (tipWidth + space + "px ");
Return autoTip;
},
Select: function (target, index, settings, flag ){
Var color = flag? Settings. highlightColor: settings. unhighlightColor;
Target. children ("div" ).eq(index).css ("background-color", color );
},
KeyOperator: function (event, autoTip, settings ){
Var evt = event | window. event;
Var autoNodes = autoTip. children ("div ");
Var kc = evt. keyCode;
Var $ this = this;
/* When the user presses a letter, delete, or return key */
If (kc> = keys. A & kc <= keys. Z | kc = keys. BACKSPACE | kc = keys. DEL ){
Var wordText = this. val ();
If (wordText. length! = 0 ){
Var param = {};
Param [settings. paramName] = wordText;
ClearTimeout (timeId );
TimeId = setTimeout (function (){
$. Post (settings. url, param, function (data ){
Var wordObj = $ (data );
If (settings. dataType = "xml "){
Var wordNodes = wordObj. find ("word ");
AutoTip.html ("");
WordNodes. each (function (I ){
Var divNode = $ ("<div>"). attr ("id", I );
// Add the traversed word to the created div and append the div to auto.
DivNode.html ($ (this). text (). appendTo (autoTip );
// The mouse has entered to add highlight
DivNode. mousemove (function (){
// If the highlight already exists, remove the highlight and change it to white.
If (index! =-1 ){
AutoTip. children ("div" ).eq(index).css ("background-color", settings. unhighlightColor );
}
Index = $ (this). attr ("id ");
((This).css ("background-color", settings. highlightColor );
});
// Move the mouse out to cancel highlighting
DivNode. mouseout (function (){
Background (this).css ("background-color", settings. unhighlightColor );
});
// Click the highlighted content
DivNode. click (function (){
$ This. val ($ (this). text ());
Index =-1;
AutoTip. hide ();
});
});
If (wordNodes. length> 0 ){
AutoTip. show ();
} Else {
AutoTip. hide ();
Index =-1;
}
}
});
}, Settings. delay );
} Else {
AutoTip. hide ();
Index =-1;
}
} Else if (kc = keys. UP | kc = keys. DOWN) {/* when the user presses the UP/DOWN key */
If (kc = keys. UP) {// UP
If (index! =-1 ){
AutoNodes.eq(index).css ("background-color", settings. unhighlightColor );
Index --;
} Else {
Index = autoNodes. length-1;
}
If (index =-1 ){
Index = autoNodes. length-1;
}
AutoNodes.eq(index).css ("background-color", settings. highlightColor );
} Else {// down
If (index! =-1 ){
AutoNodes.eq(index).css ("background-color", settings. unhighlightColor );
}
Index ++;
If (index = autoNodes. length ){
Index = 0;
}
AutoNodes.eq(index).css ("background-color", settings. highlightColor );
}
} Else if (kc = keys. PAGEUP | kc = keys. PAGEDOWN ){
Event. preventDefault ();
If (kc = keys. PAGEUP ){
If (index! =-1 ){
AutoNodes.eq(index).css ("background-color", settings. unhighlightColor );
}
If (autoNodes. length> 0 ){
Index = 0;
AutoNodes.eq(0).css ("background-color", settings. highlightColor );
}
} Else {
If (index! =-1 ){
AutoNodes.eq(index).css ("background-color", settings. unhighlightColor );
}
Index = autoNodes. length-1;
AutoNodes.eq(index).css ("background-color", settings. highlightColor );
}
} Else if (kc = keys. ENTER ){
// Enter the Enter key
// Complete the information with highlighted content
If (index! =-1 ){
$ This. val (autoNodes. eq (index). text ());
} Else {// hide if no
$ ("Body"). append ($ ("<div/>"). text ("" + $ this. val () + "in the text box is submitted! "));
$ This. get (0). blur ();
}
AutoTip. hide ();
Index =-1;
} Else if (kc = keys. ESC ){
AutoTip. hide ();
}
}
});
}) (JQuery );

Now let's analyze some common options of the above autocomplate plug-in:
Index is the index highlighted by the prompt option;
TimeId is the time that a user uses setTimeout to request the server to obtain data when entering text fields;
CssOptions is the style of the automatic prompt option. Some default styles are provided here;Copy codeThe Code is as follows: var defaults = {
Width: "auto", // default or automatic width setting
HighlightColor: "# 3399FE", // color when highlighted
UnhighlightColor: "# FFFFFF", // non-highlighted color
Css: cssOptions,
DataType: "xml", // data type returned by ajax requests
ParamName: "word", // Parameter Name of the ajax request. If you have set the id of the text field, use this attribute.
Delay: 500, // how often does ajax request a server when text fields are continuously input?
};

Keys is the value corresponding to the keyboard key;
Autocomplete is the called function. You can set the url of the ajax request and configure the parameters in the above ults. This method returns the value of the text field;
AutoTipTemplate is the prompt box and prompt menu displayed during input. A jquery object is returned;
Select is the highlight option of the prompt menu, that is, the prompt menu. target is the target object, index is the index of the option to be highlighted, and settings is
Highlighted color configuration, which is available in default ults. The defaults object attribute is assigned to the settings object through the $. extend method;
KeyOperator is a keyboard operation for text fields, which is the core function. Operation prompts and Automatic completion depend on it;
Let's take a look at the html code to see how the autocomplate plug-in is called:Copy codeThe Code is as follows: <! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN">
<Html>
<Head>
<Title> Ajax example to implement full-featured Google search </title>
<Meta http-equiv = "author" content = "hoojo">
<Meta http-equiv = "email" content = "hoojo_@126.com">
<Meta http-equiv = "content-type" content = "text/html; charset = UTF-8">
<Script type = "text/javascript" src = "jslib/jquery-1.3.2.min.js"> </script>
<Script type = "text/javascript" src = "jsliding B/jquery. autocomplete-1.2.js"> </script>
<Script type = "text/javascript">
$ (Function (){
$ (": Text"). autocomplete ("AutocomplataWordServlet", {dataType: "xml", width: "auto "});
});
</Script>
</Head>
<Body>
Enter <input type = "text"/>
<Input type = "button" value = "Go"/> <br/>
</Body>
</Html>

Let's see this code. AutocomplataWordServlet is the requested Servlet, and dataType is the type of data returned by the ajax request server. width can be used to set the width of the automatic prompt menu.
How about it? It's easy to use. Of course, you can add other configurations later, such:
Code snippetCopy codeThe Code is as follows: $ (": text"). autocomplete ("AutocomplataWordServlet ",{
Width: "auto ",
HighlightColor: "# 3355FE ",
UnhighlightColor: "# FFFFcc ",
Css: {border: "2px solid red "},
DataType: "xml ",
ParamName: "keyWord ",
Delay: 300
});

This is also possible;
Let's take a look at the AutocomplataWordServlet code:Copy codeThe Code is as follows: package com. hoo. servlet;
Import java. io. IOException;
Import javax. servlet. ServletException;
Import javax. servlet. http. HttpServlet;
Import javax. servlet. http. HttpServletRequest;
Import javax. servlet. http. HttpServletResponse;
@ SuppressWarnings ("serial ")
Public class AutocomplataWordServlet extends HttpServlet {
Public void doGet (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {
String word = request. getParameter ("word ");
Request. setAttribute ("word", word );
// System. out. println (word );
Request. getRequestDispatcher ("word. jsp"). forward (request, response );
}
Public void doPost (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {
DoGet (request, response );
}
}

Nothing can be said, that is, to obtain the keyword of the ajax request in the client text field, and then filter words on the jsp page. However, you can also use regular expressions on the client.
Or you can use regular expression filtering on the server.
Let's take a look at the content of word. jsp:Copy codeThe Code is as follows: <% @ page language = "java" contentType = "text/xml; charset = UTF-8" %>
<% @ Taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<% @ Taglib prefix = "fn" uri = "http://java.sun.com/jsp/jstl/functions" %>
<Words>
<C: if test = "$ {fn: startsWith ('abstruct ', word)}">
<Word> abstruct </word>
</C: if>
<C: if test = "$ {fn: startsWith ('anilazine', word)}">
<Word> anilazine </word>
</C: if>
<C: if test = "$ {fn: startsWith ('appeared', word)}">
<Word> appeared </word>
</C: if>
<C: if test = "$ {fn: startsWith ('autocytolysis ', word)}">
<Word> autocytolysis </word>
</C: if>
<C: if test = "$ {fn: startsWith ('apple', word)}">
<Word> apple </word>
</C: if>
<C: if test = "$ {fn: startsWith ('boolean', word)}">
<Word> boolean </word>
</C: if>
<C: if test = "$ {fn: startsWith ('Break', word)}">
<Word> break </word>
</C: if>
<C: if test = "$ {fn: startsWith ('bird ', word)}">
<Word> bird </word>
</C: if>
<C: if test = "$ {fn: startsWith ('blur', word)}">
<Word> blur </word>
</C: if>
<C: if test = "$ {fn: startsWith ('call', word)}">
<Word> call </word>
</C: if>
<C: if test = "$ {fn: startsWith ('class', word)}">
<Word> class </word>
</C: if>
<C: if test = "$ {fn: startsWith ('Card ', word)}">
<Word> card </word>
</C: if>
<C: if test = "$ {fn: startsWith ('dacnomania ', word)}">
<Word> dacnomania </word>
</C: if>
<C: if test = "$ {fn: startsWith ('document', word)}">
<Word> document </word>
</C: if>
</Words>

It is a document in xml format. It uses the jstl expression and the startsWith function for matching. If it passes through, it will appear in the xml content, and the above contentType = "text/xml; charset = UTF-8 "No, it's text/xml! This should be noted that if some browsers are not set, they cannot be parsed.
Author: hoojo
Blog: http://blog.csdn.net/IBM_hoojo

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.