Home  >  Article  >  Web Front-end  >  jQuery UI Autocomplete experience sharing_jquery

jQuery UI Autocomplete experience sharing_jquery

WBOY
WBOYOriginal
2016-05-16 17:56:10939browse
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:
Copy code The code is as follows:
[ "cnblogs","blog garden","囧月"]

For Array in JSON format, it is required to have: label and value attributes, as follows:
Copy code The code is as follows:
[{label: "blog garden", value: "cnblogs"}, {label: "囧月", value: "囧Month"}]

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:
Copy code The code is 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:
Copy code Code As follows:
[{"label": "Blog Garden", "value": "cnblogs"}, {"label": "囧月", "value": "囧月"}]

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:
Copy code The code is 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:
Copy code The code is as follows:

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
Copy code The code is as follows:

// 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)
Copy code The code is as follows:

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:
Copy code The code is as follows:

$("#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:
Copy code The code is 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:
Copy code The code is 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:
Copy code The code is as follows:

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