jQuery Autocomplete instance introduction
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 type="text" id="autocomp" />
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!

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Object-relational mapping (ORM) frameworks play a vital role in python development, they simplify data access and management by building a bridge between object and relational databases. In order to evaluate the performance of different ORM frameworks, this article will benchmark against the following popular frameworks: sqlAlchemyPeeweeDjangoORMPonyORMTortoiseORM Test Method The benchmarking uses a SQLite database containing 1 million records. The test performed the following operations on the database: Insert: Insert 10,000 new records into the table Read: Read all records in the table Update: Update a single field for all records in the table Delete: Delete all records in the table Each operation

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: <

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:

Object-relational mapping (ORM) is a programming technology that allows developers to use object programming languages to manipulate databases without writing SQL queries directly. ORM tools in python (such as SQLAlchemy, Peewee, and DjangoORM) simplify database interaction for big data projects. Advantages Code Simplicity: ORM eliminates the need to write lengthy SQL queries, which improves code simplicity and readability. Data abstraction: ORM provides an abstraction layer that isolates application code from database implementation details, improving flexibility. Performance optimization: ORMs often use caching and batch operations to optimize database queries, thereby improving performance. Portability: ORM allows developers to

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

目录1:basename()2:copy()3:dirname()4:disk_free_space()5:disk_total_space()6:file_exists()7:file_get_contents()8:file_put_contents()9:filesize()10:filetype()11:glob()12:is_dir()13:is_writable()14:mkdir()15:move_uploaded_file()16:parse_ini_file()17:

Object-relational mapping (ORM) is a technology that allows building a bridge between object-oriented programming languages and relational databases. Using pythonORM can significantly simplify data persistence operations, thereby improving application development efficiency and maintainability. Advantages Using PythonORM has the following advantages: Reduce boilerplate code: ORM automatically generates sql queries, thereby avoiding writing a lot of boilerplate code. Simplify database interaction: ORM provides a unified interface for interacting with the database, simplifying data operations. Improve security: ORM uses parameterized queries, which can prevent security vulnerabilities such as SQL injection. Promote data consistency: ORM ensures synchronization between objects and databases and maintains data consistency. Choose ORM to have

jQuery is a popular JavaScript library widely used in web development. During web development, it is often necessary to dynamically add new rows to tables through JavaScript. This article will introduce how to use jQuery to add new rows to a table, and provide specific code examples. First, we need to introduce the jQuery library into the HTML page. The jQuery library can be introduced in the tag through the following code:
