This article mainly introduces an introduction to jQuery Autocomplete. jQuery UI Autocomplete is the autocomplete component of jQuery UI. It is the most powerful and flexible Autocomplete I have ever used. It supports local Array/JSON arrays and Array requests through ajax. /JSON array, JSONP, and Function (the most flexible) methods to obtain data.
jQuery UI Autocomplete is the autocomplete component of jQuery UI. It is the most powerful and flexible Autocomplete I have ever used. It supports local Array/JSON arrays, Array/JSON arrays requested through ajax, and JSONP , and Function (the most flexible) to obtain data.
Supported data sources
jQuery UI Autocomplete mainly supports two data formats: string Array and JSON.
There is nothing special about the ordinary Array format, as follows:
["bjpowernode","动力节点","李四"]
For Array in JSON format, it is required to have: label and value attributes, as follows:
[{label: "动力节点", value: "bjpowernode"}, {label: "李四", value: "李四"}]
The label attribute is used to display in the autocomplete pop-up menu, and the value attribute is the value assigned to the text box after selection.
If one of the attributes is not specified, use the other attribute instead (that is, value and label have the same value), as follows:
[{label: "bjpowernode"}, {label: "李四"}] [{value: "bjpowernode"}, {value: "李四"}]
If neither label nor value is specified, It cannot be used for autocomplete prompts.
Also note that the JSON key output from the server must be in double quotes, as follows:
[{"label": "动力节点", "value": "bjpowernode"}, {"label": "李四", "value": "李四"}]
Otherwise, a parsererror error may occur.
Main parameters
The commonly used parameters of jQuery UI Autocomplete are:
1.Source: used to specify the data source, the type is String, Array, Function
String: Server-side address used for ajax request, returns Array/JSON format
Array: String Array or JSON array
Function(request, response): Get the input value through request.term, response([Array]) to present the data; (JSONP is this way)
2.minLength: When the length of the string in the input box reaches minLength, activate Autocomplete
3.autoFocus: When the Autocomplete selection menu pops up, automatically select The first
4.delay: that is, how many milliseconds to delay to activate Autocomplete
Other less commonly used ones will not be listed.
How to use
If there is the following input box on the page:
<input>
AJAX request
By specifying the source as the server-side address To implement, as follows:
$("#autocomp").autocomplete({ source: "remote.ashx", minLength: 2 });
Then receive it on the server side and output the corresponding results. Note that the default passed parameter name is term:
public void ProcessRequest(HttpContext context) { // 查询的参数名称默认为term string query = context.Request.QueryString["term"]; context.Response.ContentType = "text/javascript"; //输出字符串数组 或者 JSON 数组 context.Response.Write("[{\"label\":\"动力节点\",\"value\":\"bjpowernode\"},{\"label\":\"李四\",\"value\":\"李四\"}]"); }
Local Array/JSON array
// 本地字符串数组 var availableTags = [ "C#", "C++", "Java", "JavaScript", "ASP", "ASP.NET", "JSP", "PHP", "Python", "Ruby" ]; $("#local1").autocomplete({ source: availableTags }); // 本地json数组 var availableTagsJSON = [ { label: "C# Language", value: "C#" }, { label: "C++ Language", value: "C++" }, { label: "Java Language", value: "Java" }, { label: "JavaScript Language", value: "JavaScript" }, { label: "ASP.NET", value: "ASP.NET" }, { label: "JSP", value: "JSP" }, { label: "PHP", value: "PHP" }, { label: "Python", value: "Python" }, { label: "Ruby", value: "Ruby" } ]; $("#local2").autocomplete({ source: availableTagsJSON });
Callback Function method
Obtain custom data by specifying the source as a custom function. The function mainly has two parameters (request, response), respectively. Used to obtain input values and present results
Local Array method to obtain data (imitating Sina Weibo login)
var hosts = ["gmail.com", "live.com", "hotmail.com", "yahoo.com", "bjpowernode.com", "火星.com", "李四.com"]; $("#email1").autocomplete({ autoFocus: true, source: function(request, response) { var term = request.term, //request.term为输入的字符串 ix = term.indexOf("@"), name = term, // 用户名 host = "", // 域名 result = []; // 结果 result.push(term); // result.push({ label: term, value: term }); // json格式 if (ix > -1) { name = term.slice(0, ix); host = term.slice(ix + 1); } if (name) { var findedHosts = (host ? $.grep(hosts, function(value) { return value.indexOf(host) > -1; }) : hosts), findedResults = $.map(findedHosts, function(value) { return name + "@" + value; //返回字符串格式 // return { label: name + " @ " + value, value: name + "@" + value }; // json格式 }); result = result.concat($.makeArray(findedResults)); } response(result);//呈现结果 } });
JSONP method to obtain data
Taken directly from the official DEMO, send an ajax request to the remote server, then process the return result, and finally present it through response:
$("#jsonp").autocomplete({ source: function(request, response) { $.ajax({ url: "http://ws.geonames.org/searchJSON", dataType: "jsonp", data: { featureClass: "P", style: "full", maxRows: 12, name_startsWith: request.term }, success: function(data) { response($.map(data.geonames, function(item) { return { label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName, value: item.name } })); } }); }, minLength: 2 });
Main events
jQuery UI Autocomplete has some events that can be used for additional control at some stages:
1.create(event, ui): When Autocomplete is created, you can in this event, Have some control over the appearance
2.search(event, ui): Before starting the request, you can return false in this event to cancel the request
3.open (event, ui): When the Autocomplete result list pops up
4.focus(event, ui): When any item in the Autocomplete result list gets focus, ui.item is the item that gets the focus
5.select(event, ui): When any item in the Autocomplete result list is selected, ui.item is the selected item
6.close(event, ui ): When the Autocomplete result list is closed
7.change(event, ui): When the value changes, ui.item is the selected item
The events of these events The item attribute of the ui parameter (if any) has label and value attributes by default. Regardless of whether the data set in the source is an Array or a JSON array, there are three types:
["bjpowernode","动力节点","李四"] [{label: "动力节点", value: "bjpowernode"}, {label: "李四", value: "李四"}] [{label: "动力节点", value: "bjpowernode", id: "1"}, {label: "李四", value: "李四", id: "2"}]
If it is the third type If so, you can also get the value of ui.item.id.
These events can be bound in 2 ways, as follows:
// 在参数中 $("#autocomp").autocomplete({ source: availableTags , select: function(e, ui) { alert(ui.item.value) } }); // 通过bind来绑定 $("#autocomp").bind("autocompleteselect", function(e, ui) { alert(ui.item.value); });
The event name used to bind through bind is "autocomplete" + event name , such as "select" is "autocompleteselect".
Autocomplete for multiple values
Under normal circumstances, the autocomplete of the input box only requires one value (such as: javascript); if multiple values are needed (such as : javascript, c#, asp.net), you need to bind some events for additional processing:
1. Return false in the focus event to prevent the value of the input box from being replaced by a single value of autocomplete
2. Combine multiple values in the select event
3. Do some processing in the keydown event of the element, the reason is the same as 1
4. Use the callback function source to get the last input value and present the result
Or just take the official DEMO code directly:
// 按逗号分隔多个值 function split(val) { return val.split(/,\s*/); } // 提取输入的最后一个值 function extractLast(term) { return split(term).pop(); } // 按Tab键时,取消为输入框设置value function keyDown(event) { if (event.keyCode === $.ui.keyCode.TAB && $(this).data("autocomplete").menu.active) { event.preventDefault(); } } var options = { // 获得焦点 focus: function() { // prevent value inserted on focus return false; }, // 从autocomplete弹出菜单选择一个值时,加到输入框最后,并以逗号分隔 select: function(event, ui) { var terms = split(this.value); // remove the current input terms.pop(); // add the selected item terms.push(ui.item.value); // add placeholder to get the comma-and-space at the end terms.push(""); this.value = terms.join(", "); return false; } }; // 多个值,本地数组 $("#local3").bind("keydown", keyDown) .autocomplete($.extend(options, { minLength: 2, source: function(request, response) { // delegate back to autocomplete, but extract the last term response($.ui.autocomplete.filter( availableTags, extractLast(request.term))); } })); // 多个值,ajax返回json $("#ajax3").bind("keydown", keyDown) .autocomplete($.extend(options, { minLength: 2, source: function(request, response) { $.getJSON("remoteJSON.ashx", { term: extractLast(request.term) }, response); } }));
Related recommendations:
How to use autocomplete in Ionic3 UI components
Recommend 10 commonly used AutoComplete example usages, welcome to download!
The above is the detailed content of jQuery Autocomplete instance introduction. For more information, please follow other related articles on the PHP Chinese website!

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 English version
Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
