Home Web Front-end JS Tutorial jQuery autocomplate self-expanding plug-in, auto-complete sample code_jquery

jQuery autocomplate self-expanding plug-in, auto-complete sample code_jquery

May 16, 2016 pm 06:09 PM
jquery automatic completion

Copy code The code is as follows:

But it is compatible with browsers. It has been tested to be compatible with IE6 and 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("[" search.val() "] in the text box has been submitted!");
$("#auto").hide();
index = - 1;
});*/
return this.each(function () {
$this.val();
});
},
autoTipTemplate: function (input, settings) {
var inputOffset = input.offset();
var autoTip = $("
").css(settings.css).hide()
.css("top", inputOffset.top input.height() 5 "px")
.css("left", inputOffset.left "px");
var space = $.browser.mozilla ? 2 : 6;//兼容浏览器
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;
/* 当用户按下字母或是delete 或是退格键*/
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 = $("
").attr("id", i);
//将遍历的单词加入到创建的div中,然后把该div追加到auto中
divNode.html($(this).text()).appendTo(autoTip);
//鼠标已进去,添加高亮
divNode.mousemove(function () {
//如果已经存在高亮,去掉高亮改为白色
if (index != -1) {
autoTip.children("div").eq(index).css("background-color", settings.unhighlightColor);
}
index = $(this).attr("id");
$(this).css("background-color", settings.highlightColor);
});
//鼠标移出,取消高亮
divNode.mouseout(function () {
$(this).css("background-color", settings.unhighlightColor);
});
//点击高亮内容
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) {/*当用户按下上下键*/
if (kc == keys.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 {//向下
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) {
//回车键
//有高亮内容就补全信息
if (index != -1) {
$this.val(autoNodes.eq(index).text());
} else {//没有就隐藏
$("body").append($("
").text("文本框中的【" $this.val() "】被提交了!"));
$this.get(0).blur();
}
autoTip.hide();
index = -1;
} else if (kc == keys.ESC) {
autoTip.hide();
}
}
});
})(jQuery);

现在来分析上面的autocomplate插件的一些常用选项:
index就是选择提示选项高亮的索引;
timeId是当用户在文本域输入时,利用setTimeout进行ajax请求服务器获得数据的而返回的时间;
cssOptions是自动提示选项的样式,这里给出了一些默认的样式;
复制代码 代码如下:

var defaults = {
width: "auto",//Default or automatically set width
highlightColor: "#3399FE",//Color when highlighting
unhighlightColor: "# FFFFFF",//Color when not highlighted
css: cssOptions,
dataType: "xml",//Ajax request return data type
paramName: "word",//Ajax request parameter name , if you have set the id of the text field, then use this attribute
delay: 500, //When the text field is continuously input, how often ajax requests the server
};

keys is the value corresponding to the keyboard key;
autocomplete is the function called, in which you can set the URL of the ajax request and configure the parameters that appear in the defaults above. This method returns the value of the text field;
autoTipTemplate is the prompt box and prompt menu displayed when inputting, and returns a jquery object;
select is the selection prompt menu, which is the highlighted option of the prompt menu. The target is of course the target object, and the index is the one that will be highlighted. The index of the bright option, settings is the
highlight color configuration, which is included in the defaults. The properties of the defaults object are assigned to the settings object through the $.extend method;
keyOperator is a keyboard operation for the text field. This is the core function; operation prompts and automatic completion depend on it;
See below Look at the html code and see how the autocomplate plug-in is called:
Copy the code The code is as follows:




Ajax example, implementing Google Search completion function







Please enter:






Look at this code. AutocomplataWordServlet is the requested Servlet. dataType is the type of data returned by the ajax request server. width can set the width of the automatic prompt menu.
How about it? It’s relatively simple to use. Of course, you can also add other configurations later, such as:
Code snippet
Copy code The 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;
Look at the code of AutocomplataWordServlet:
Copy the code The 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);
}
}

There is nothing to say, just get the keywords of the ajax request in the client text field, and then perform word filtering in the jsp page. However, you can also use regular
on the client or regular filtering on the server.
Look at the content of word.jsp below:
Copy the code The 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>

abstruct


anilazine

appeared


autocytolysis


apple


boolean


break

< ;c:if test="${fn:startsWith('bird', word)}">
bird

< c:if test="${fn:startsWith('blur', word)}">
blur


call


class


card


dacnomania


document



is a document in xml format. By using jstl expression and matching with startsWith function, if passed, it will appear in the xml content, and you can see the above contentType="text/xml; charset=UTF- 8"? It's text/xml! Please note this, some browsers will not be able to parse it if it is not configured.
Author: hoojo
blog: http://blog.csdn.net/IBM_hoojo
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of jQuery reference methods: Quick start guide Detailed explanation of jQuery reference methods: Quick start guide Feb 27, 2024 pm 06:45 PM

Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

In-depth analysis: jQuery's advantages and disadvantages In-depth analysis: jQuery's advantages and disadvantages Feb 27, 2024 pm 05:18 PM

jQuery is a fast, small, feature-rich JavaScript library widely used in front-end development. Since its release in 2006, jQuery has become one of the tools of choice for many developers, but in practical applications, it also has some advantages and disadvantages. This article will deeply analyze the advantages and disadvantages of jQuery and illustrate it with specific code examples. Advantages: 1. Concise syntax jQuery's syntax design is concise and clear, which can greatly improve the readability and writing efficiency of the code. for example,

How to remove the height attribute of an element with jQuery? How to remove the height attribute of an element with jQuery? Feb 28, 2024 am 08:39 AM

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

How to tell if a jQuery element has a specific attribute? How to tell if a jQuery element has a specific attribute? Feb 29, 2024 am 09:03 AM

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

Understand the role and application scenarios of eq in jQuery Understand the role and application scenarios of eq in jQuery Feb 28, 2024 pm 01:15 PM

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

See all articles