JQuery autocomplate Self-extension, AutoComplete sample code _jquery

Source: Internet
Author: User
Copy Code code as follows:

However, the compatibility of the browser, tested compatible ie6+, firefox3.5+
First Look at Autocomplate.js:
;(function ($) {
var index =-1;
var Timeid;
var cssoptions = {
"Border": "1px solid black",
"Background-color": "White",
"Position": "Absolute"/*,
"Font": "Normal 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 ("In the text box" + search.val () + "" was committed! ");
$ ("#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 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 the letter or delete or the backspace bar *
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);
Mouse is in, add highlight
Divnode.mousemove (function () {
If there is already a highlight, remove the highlight and change 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);
});
Mouse out, remove highlight
Divnode.mouseout (function () {
$ (this). CSS ("Background-color", Settings.unhighlightcolor);
});
Click on 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 and down key/
if (KC = = keys. UP) {//upward
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
Fill in the full information with the highlighted content
if (index!=-1) {
$this. Val (Autonodes.eq (index). text ());
else {//No Hidden
$ ("Body"). Append ($ ("<div/>"). Text ("" in the text Box + $this. val () + "" was committed! "));
$this. Get (0). blur ();
}
Autotip.hide ();
index =-1;
else if (KC = = keys. ESC) {
Autotip.hide ();
}
}
});
}) (JQuery);

Now to analyze some of the common options for the Autocomplate plug-in above:
Index is the choice of the hint option highlighted indexes;
Timeid is the time when the user enters the text field and uses the settimeout to request the server to obtain the data.
Cssoptions is the style of the automatic prompt option, which gives some default styles;
Copy Code code as follows:

var defaults = {
Width: "Auto",//default or auto set widths
HighlightColor: "#3399FE",//color when highlighted
Unhighlightcolor: "#FFFFFF",//color when not highlighted
Css:cssoptions,
DataType: "xml",//ajax request return data type
ParamName: "word",//ajax the requested parameter name, if you have the ID of the Set Text field, use this property
delay:500,//when the text field is constantly entered, how often does Ajax request a server
};

Keys are the corresponding values of keyboard keys;
AutoComplete is called function, you can set the URL of the AJAX request inside, and configure the parameters appearing in the defaults above, this method returns the value of the text field;
Autotiptemplate is the display of the prompt box, hint menu, return is a jquery object;
Select is the highlight option for the Hint menu, which is definitely the target object, and index is the one that will be highlighted.
Highlight the color configuration, which is available in the default defaults. is to assign a property of a defaults object to the settings object by means of the $.extend method;
Keyoperator is the keyboard operation for the text field, which is the core function, the operation prompt, the automatic completion depends on it;
Let's look at the HTML code to see how to invoke the Autocomplate plugin:
Copy code code as follows:

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
<title> Ajax example, to achieve Google search full functionality </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" > Br><script type= "Text/javascript" src= "jslib/jquery-1.3.2.min.js" ></script>
<script type= "text/" JavaScript "src=" Jslib/jquery.autocomplete-1.2.js ></script>
<script type= "Text/javascript" >
$ (function () {
$ (": Text"). AutoComplete ("Autocomplatawordservlet", {dataType: "xml", Width: "Auto"});
});
</script>
<body>
Please enter: <input type= "text"/>
<input type= "but Ton "value=" Go "/><br/><br/>
</body>

Look at this code Autocomplatawordservlet is the requested Servlet,datatype is the AJAX request server-side return data type, width can set the width of the automatic hint menu.
How to use it is simpler. Of course, you can also add other configuration, such as:
Code fragment
Copy Code code 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;
Look at the Autocomplatawordservlet code:
Copy Code code 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 to say is to get the keyword of the AJAX request for the client text field and then filter the word in the JSP page. But you can also use regular on the client
Or it is possible to use regular filtering on the server side.
Here's what word.jsp:
Copy Code code 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>

is an XML-formatted document that uses the JSTL expression to match the StartsWith function, and if it is in the XML content, see the Contenttype= "Text/xml;" Charset=utf-8 "No, is Text/xml Oh!" Note that if you do not set up some browsers can not be resolved.
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.