jQuery UI Autocomplete mainly supports two data formats: string Array and JSON.
There is nothing special about the ordinary Array format, as follows:
For Array in JSON format, it is required to have: label and value attributes, as follows:
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, it will be replaced by the other attribute (i.e. value and label value are the same), as follows:
[{label: "cnblogs"}, {label: "囧月"}]
[{value: "cnblogs"}, {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:
Otherwise a parsererror error may occur.
Main parameters
Commonly used parameters of jQuery UI Autocomplete are:
Source: used to specify the data source, type is String, Array, Function
String: server-side address used for ajax request, returned Array/JSON format
Array: i.e. string array or JSON array
Function(request, response): Get the input value through request.term, response([Array]) to present the data; (JSONP is this Method)
minLength: When the length of the string in the input box reaches minLength, activate Autocomplete
autoFocus: When the Autocomplete selection menu pops up, automatically select the first one
delay: how many milliseconds to delay activating Autocomplete
Others that are not commonly used will not be listed.
Usage
Suppose there is the following input box on the page:
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. Please pay attention to the default delivery The parameter name is term:
public void ProcessRequest(HttpContext context )
{
// The query parameter name defaults to term
string query = context.Request.QueryString["term"];
context.Response.ContentType = "text/javascript";
//Output string array or JSON array
context.Response.Write("[{"label":"blog garden","value":"cnblogs"},{"label":"囧月" ,"value":"囧月"}]");
}
Local Array/JSON array
// Local string array
var availableTags = [
"C#",
"C ",
"Java",
"JavaScript",
"ASP",
"ASP.NET",
"JSP",
"PHP",
"Python",
"Ruby"
];
$("#local1").autocomplete({
source: availableTags
});
// Local json array
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
Acquire custom data by specifying the source as a custom function. The function mainly has 2 parameters (request, response), which are used to obtain the input value, Present results
Get data in local Array mode (imitate Sina Weibo login)
var hosts = ["gmail.com", "live.com", "hotmail.com", "yahoo.com", "cnblogs.com", "Mars.com", "囧月. com"];
$("#email1").autocomplete({
autoFocus: true,
source: function(request, response) {
var term = request.term, //request .term is the input string
ix = term.indexOf("@"),
name = term, // Username
host = "", // Domain name
result = [] ; // result
result.push(term);
// result.push({ label: term, value: term }); // json format
if (ix > -1) {
name = term.slice(0, ix);
host = term.slice(ix 1);
}
if (name) {
var foundHosts = (host ? $. grep(hosts, function(value) {
return value.indexOf(host) > -1;
}) : hosts),
findedResults = $.map(findedHosts, function(value) {
return name "@" value; //Return string format
// return { label: name " @ " value, value: name "@" value }; // json format
});
result = result.concat($.makeArray(findedResults));
}
response(result);//Present the results
}
});
Get data via JSONP
Get it 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:
create(event, ui): When Autocomplete is created, you can use this event in , some control over the appearance
search(event, ui): Before starting the request, you can return false in this event to cancel the request
open(event, ui): When Autocomplete's result list pops up
focus(event, ui): When any item in Autocomplete's result list gets focus, ui.item is the item that gets focus
select(event, ui): When any item in Autocomplete's result list is selected, ui.item is Selected item
close(event, ui): When the result list of Autocomplete is closed
change(event, ui): When the value changes, ui.item is the selected item
The ui parameters of these events The item attribute (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, as follows:
["cnblogs","blog garden","囧月"]
[{label: "blog garden", value: " cnblogs"}, {label: "囧月", value: "囧月"}]
[{label: "囧月园", value: "cnblogs", id: "1"}, {label: "囧月" month", value: "囧月", id: "2"}]
If it is the third type, you can also get the value of ui.item.id.
These events can be bound in 2 ways, as follows:
// In parameters
$("#autocomp").autocomplete({
source: availableTags
, select: function(e, ui) {
alert(ui.item .value)
}
});
// Bind through bind
$("#autocomp").bind("autocompleteselect", function(e, ui) {
alert(ui.item.value);
});
The event name used by binding through bind is "autocomplete". The 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 Bind some events for additional processing:
Return false in the focus event to prevent the value of the input box from being replaced by a single value of autocomplete
Combine multiple values in the select event
Do it in the keydown event of the element Some processing, the reason is the same as 1
Use callback function source to get the last input value and present the result
Or just take the official DEMO code directly:
// Separate multiple values by commas
function split(val) {
return val.split( /,s*/);
}
//Extract the last value of the input
function extractLast(term) {
return split(term).pop();
}
// When pressing the Tab key, cancel setting the value for the input box
function keyDown(event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this). data("autocomplete").menu.active) {
event.preventDefault();
}
}
var options = {
// Get focus
focus: function( ) {
// prevent value inserted on focus
return false;
},
// When selecting a value from the autocomplete pop-up menu, add it to the end of the input box and separate it with commas
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;
}
};
// Multiple values, local array
$("#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)));
}
}));
// Multiple values, ajax returns json
$("#ajax3").bind("keydown", keyDown)
.autocomplete($.extend(options, {
minLength: 2,
source: function(request, response) {
$.getJSON("remoteJSON.ashx", {
term: extractLast(request.term)
}, response);
}
}));
End
Finally, put the code: Click to download.
For more information, please see the jQuery UI Autocomplete official demo: http://jqueryui.com/demos/autocomplete

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


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

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1
Powerful PHP integrated development environment

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

Dreamweaver Mac version
Visual web development tools
