JQuery UI AutoComplete experience sharing _jquery

Source: Internet
Author: User
Tags extend string format jquery ui autocomplete
Supported data sources
The JQuery UI autocomplete mainly supports string array, json two data formats.
The normal array format is nothing special, as follows:
Copy Code code as follows:
["Cnblogs", "Blog Park", "embarrassing month"]

For JSON-formatted array, the: Label, Value property is required, as follows:
Copy Code code as follows:
[{label: "blog Park", Value: "Cnblogs"}, {label: "Embarrassing Month", Value: "The Month"}]

Where the Label property is used for display in the AutoComplete pop-up menu, and the Value property is the values that are assigned to the text box when selected.
If you do not specify one of the properties, replace it with another property (that is, value and label values), as follows:
Copy Code code as follows:

[{label: ' Cnblogs '}, {label: ' Embarrassing Month '}]
[{value: ' Cnblogs '}, {value: ' Embarrassing month '}]

If neither label nor value is specified, the prompt for AutoComplete cannot be used.
It is also important to note that the key for JSON output from the server must be in double quotes, as follows:
Copy Code code as follows:
[{"Label": "Blog Park", "Value": "Cnblogs"}, {"label": "Embarrassing Month", "value": "Embarrassing Month"}]

Otherwise, there may be a parsererror error.
The main parameters
The common parameters for JQuery UI autocomplete are:
Source: Used to specify a data source, type string, Array, Function
String: Server-side address for Ajax requests, returning Array/json format
Array: An array of strings or JSON arrays
Function (Request, Response): Request.term Gets the input value, response ([Array]) to render the data; (Jsonp is this way)
MinLength: Activate AutoComplete When the length of the string in the input box reaches minlength
Autofocus: When the AutoComplete selection menu pops up, automatically selects the first
Delay: That is, how many milliseconds to delay activation autocomplete
Other less common is not listed.
How to use
If the page has the following input box:
<input type= "text" id= "Autocomp"/>
Ajax request
Implemented by specifying source as the address of the server side, as follows:
Copy Code code as follows:

$ ("#autocomp"). AutoComplete ({
Source: "Remote.ashx",
Minlength:2
});

Then receive on the server side and output the corresponding result, note that the parameter name passed by default is term:
Copy Code code as follows:

public void ProcessRequest (HttpContext context)
{
The parameter name of the query 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\": \ "embarrassing month \", \ "value\": "" The Month "}]");
}

Local Array/json Array
Copy Code code 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 Mode
By specifying source as a custom function to achieve custom data acquisition, the function has 2 parameters (Request,response), which are used to get the value of the input, render the result
Local array method to get data (imitate Sina Weibo login)
Copy Code code as follows:

var hosts = ["gmail.com", "live.com", "hotmail.com", "yahoo.com", "cnblogs.com", "Mars. com", "embarrassing month. com"];
$ ("#email1"). AutoComplete ({
Autofocus:true,
Source:function (Request, Response) {
var term = request.term,//request.term for input string
IX = Term.indexof ("@"),
name = term,//user name
Host = "",//Domain name
result = []; Results
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);//Render Results
}
});

Jsonp way to get data
Directly from the official demo, by sending Ajax requests to the remote server, and then processing the return results, and finally through the response to render:
Copy Code code 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
});

The main Event
The JQuery UI autocomplete Some of the events that can be used to control additional controls at some stage:
Create (event, UI): When AutoComplete is created, you can have some control over the appearance in this event
Search (event, UI): You can return false in this event to cancel the request before you start the request
Open (Event, UI): AutoComplete's results list pops up
Focus (event, UI): AutoComplete results list when any one of the items gets the focus, Ui.item is the item
Select (Event, UI): AutoComplete results list when any one of the items is selected, Ui.item is the selected item
Close (event, UI): AutoComplete results list is closed
Change (event, UI): When the value changes, Ui.item is the selected item
The Item property of the UI parameters for these events, if any, has a label and Value property by default, regardless of whether the data set in source is array or JSON, the following 3:
Copy Code code as follows:

["Cnblogs", "Blog Park", "embarrassing month"]
[{label: "blog Park", Value: "Cnblogs"}, {label: "Embarrassing Month", Value: "The Month"}]
[{label: "blog Garden", Value: "Cnblogs", ID: "1"}, {label: "Embarrassing Month", Value: "Embarrassing month", ID: "2"}]

If it is the third, you can also get the value of ui.item.id.
These events can be bound in 2 different ways, as follows:
Copy Code code as follows:

In the parameter
$ ("#autocomp"). AutoComplete ({
Source:availabletags
, Select:function (E, UI) {
Alert (Ui.item.value)
}
});
Bind by Bind
$ ("#autocomp"). Bind ("Autocompleteselect", Function (E, UI) {
alert (Ui.item.value);
});

The event name used for binding by BIND is "AutoComplete" + event name, such as "select" is "Autocompleteselect".
AutoComplete of multiple values
In general, the AutoComplete of an input box requires only one value (for example, JavaScript), and if multiple values (such as: javascript,c#,asp.net) are required, some events need to be bound 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
Combining multiple values in a select event
KeyDown events in the element do some processing for the same reason as 1
Use the source of the callback function method to get the last value entered and render the result
Or the code that takes the official demo directly:
Copy Code code as follows:

Separate multiple values by commas
Function Split (val) {
Return Val.split (/,\s*/);
}
Extracts the last value of the input
function Extractlast (term) {
Return split (term). Pop ();
}
When you press the TAB key, Cancel to set 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 you select a value from the AutoComplete pop-up menu, add to the end of the input box, separated by a comma
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 in 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 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, see the jquery UI AutoComplete official Demo: Http://jqueryui.com/demos/autocomplete

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.