Supported data sources
JQuery UI Autocomplete mainly supports two data formats: String Array and JSON.
The common Array format is as follows:
Copy codeThe Code is as follows: ["cnblogs", "", ""]
For arrays in JSON format, the following attributes are required: label and value:
Copy codeThe Code is as follows: [{label: "", value: "cnblogs" },{ label: "", value: ""}]
The label attribute is used to display in the autocomplete pop-up menu, while the value attribute is the value assigned to the text box after selection.
If one of the attributes is not specified, use another attribute instead (that is, the value is the same as the label value), as shown below:
Copy codeThe Code is as follows:
[{Label: "cnblogs" },{ label: ""}]
[{Value: "cnblogs" },{ value: ""}]
If neither label nor value is specified, it cannot be used for autocomplete prompts.
Note that the JSON key output from the server must be enclosed in double quotation marks as follows:
Copy codeThe Code is as follows: [{"label": "", "value": "cnblogs" },{ "label": "", "value ": ""}]
Otherwise, parsererror may occur.
Main Parameters
Common Parameters of jQuery UI Autocomplete include:
Source: used to specify the data Source, type: String, Array, Function
String: the server address used for ajax requests. Array/JSON format is returned.
Array: A String Array or a JSON Array.
Function (request, response): Get the input value through request. term, response ([Array]) to present data; (JSONP is in this way)
MinLength: when the length of a string in the input box reaches minLength, Autocomplete is activated.
AutoFocus: When the Autocomplete selection menu is displayed, the first one is automatically selected.
Delay: the delay in how many milliseconds to activate Autocomplete
Other less commonly used items are not listed.
Usage
If the following input box is displayed on the page:
<Input type = "text" id = "autocomp"/>
AJAX request
You can specify source as the server address as follows:
Copy codeThe Code is 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 parameter name is "term:
Copy codeThe Code is as follows:
Public void ProcessRequest (HttpContext context)
{
// The default query parameter name is 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 \": \ "monthly subscription \", \ "value \": \ "monthly subscription \"}] ");
}
Local Array/JSON Array
Copy codeThe 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
You can specify source as a user-defined function to obtain user data. The function mainly has two parameters (request and response) for obtaining input values and rendering results respectively.
Obtain data using local Array (IMITATING Sina Weibo login)
Copy codeThe Code is as follows:
Var hosts = ["gmail.com", "live.com", "hotmail.com", "yahoo.com", "cnblogs.com", "Mars. com", "yuyue. com"];
$ ("# Email1"). autocomplete ({
AutoFocus: true,
Source: function (request, response ){
Var term = request. term, // request. term is the input string
Ix = term. indexOf ("@"),
Name = term, // User name
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 findedHosts = (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 result
}
});
Get data using JSONP
Directly from the official DEMO, send an ajax request to the remote server, process the returned results, and then display the results through response:
Copy codeThe 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
});
Major Events
JQuery UI Autocomplete has some events that can be used for additional control at some stages:
Create (event, ui): when creating Autocomplete, you can control the appearance in this event.
Search (event, ui): Before starting a request, you can return false in this event to cancel the request.
Open (event, ui): When the Autocomplete result list is displayed
Focus (event, ui): if any item in the Autocomplete result list obtains focus, ui. item is the item that obtains focus.
Select (event, ui): When any item in the Autocomplete result list is selected, ui. item is selected
Close (event, ui): When the Autocomplete result list is closed
Change (event, ui): When the value changes, ui. item is the selected item
By default, the item attributes (if any) of the ui parameters of these events have the label and value attributes, regardless of whether the data set in source is an Array or a JSON Array:
Copy codeThe Code is as follows:
["Cnblogs", "", ""]
[{Label: "", value: "cnblogs" },{ label: "", value: ""}]
[{Label: "", value: "cnblogs", id: "1" },{ label: "", value: "", id: "2"}]
For example, you can obtain the value of ui. item. id.
These events can be bound in two ways:
Copy codeThe Code is as follows:
// In the Parameter
$ ("# 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 for bind binding is "autocomplete" + event name. For example, "select" is "autocompleteselect ".
Autocomplete of multiple values
Generally, the autocomplete in the input box only requires one value (for example, javascript). If multiple values (for example, javascript, c #, asp.net) are required ), you need to bind some events for additional processing:
Returns 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 a select event
Perform some processing on the keydown event of the element for the same reason as 1
Use the callback function source to obtain the final input value and display the result.
Take the official DEMO code directly:
Copy codeThe Code is as follows:
// Separate multiple values by commas
Function split (val ){
Return val. split (/, \ s */);
}
// Extract the last input value
Function extractLast (term ){
Return split (term). pop ();
}
// When you press the Tab key, cancel setting value for the input box
Function keyDown (event ){
If (event. keyCode ===$. ui. keyCode. TAB &&
$ (This). data ("autocomplete"). menu. active ){
Event. preventDefault ();
}
}
Var options = {
// Obtain the 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 on: Click to download.
For more information, see jQuery UI Autocomplete official Demo: http://jqueryui.com/demos/autocomplete