Autocomplete in JQueryUI, jqueryui
JQuery UI is a JQuery-based open-source JavaScript webpage user interface code library. Visual controls that contain underlying user interaction, animation, special effects, and replaceable themes include Accordion, Autocomplete, ColorPicker, Dialog, Slider, Tabs, DatePicker, magniier, ProgressBar, among them, Autocomplete can easily help us implement smart prompts similar to Baidu search. You can download the latest JQuery UI from the official JQuery UI website.
I. First, let's take a look at the important attributes provided by JQueryUI:
1.AutoFocus: Whether to automatically select the first item when the smart prompt box appears. The default value is false, that is, not selected.
2.Delay: The Search latency after pressing the button. The default value is 300 ms.
3.Disabled: Whether to disable auto-completion. The default value is false.
4.MinLength: The minimum number of characters required to trigger the auto-completion function.
5.Source: Specifies the data source in the smart prompt drop-down box. Three types are supported.
ArrayIt is mainly used to provide localized data and supports two formats: String Array ["Choice1", "Choice2"] And Json format array of tag and value attributes [{label: "Choice1 ", value: "value1"},...]
String, Used for the remote address link of an ajax request, returns an Array or a Json string.
FunctionCallback function, the most flexible method, can be used to return any data source to achieve automatic completion, which contains two parametersrequest,responsePassrequest.term To obtain the value entered by the user.response(argument)To display the obtained data source.
Ii. JQuery UI also provides some useful methods:
1.Close (): Close the intelligent prompt selection box.
2.Destroy (): Destroy the intelligent prompt selection box and delete all elements generated by the box to restore them to the initial state.
3.Disable (): Disable auto-completion.
4.Enable (): Enable auto-completion.
Iii. Main events include:
1.Change (event, ui): When the value changes, ui. item is selected.
2.Close (event, ui): The Smart prompt box is closed.
3.Create (event, ui): When a smart prompt box is created, you can control the appearance in this event.
4.Focus (event, ui): When any item in the smart prompt list gets the focus, ui. item is the item that gets the focus.
5.Open (event, ui): Occurs when the smart prompt box is opened or updated.
6.Response (event, ui): It occurs before the smart prompt box is displayed after the search is complete. You can process the display items in this event.
7.Search (event, ui): When a request occurs before it starts, you can return false in this event to cancel the request.
8.Select (event, ui): When any item in the smart prompt box is selected, ui. item is selected.
<% @ Page Language = "C #" AutoEventWireup = "true" %> <! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN "" http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "> <Html xmlns =" http://www.w3.org/1999/xhtml "> <Head runat =" server "> <title> Jquery UI Autocomplete </title> <link rel =" stylesheet "href ="/themes/base/jquery.ui.all.css "/> <script type = "text/javascript" src = "/js/jquery-1.8.2.js"> </script> <script type = "text/javascript" src = "/js/jquery. ui. core. min. js "> </script> <script type =" text/javascript "src ="/js/jquery. ui. widget. min. js "> </script> <script type =" text/javascript "src ="/js/jquery. ui. position. min. js "> </script> <script type =" text/javascript "src ="/js/jquery. ui. menu. min. js "> </script> <script type =" text/javascript "src ="/js/jquery. ui. autocomplete. min. js "> </script> Select: function (event, ui ){
// Submit the search...
}, MinLength: 2, autoFocus: false, delay: 500}) ;}); </script> </body>
In the preceding example, a link request is sent to the remote field. You must set dataType to "jsopn" format, or use the $. getJSON function. Response traverses all data items in json and returns the name of each item. Note that label indicates the text displayed for each item in the smart prompt box, and value indicates the value of each item, that is, the value assigned to the search box after this item is selected. In addition, we can add a local cache to repeatedly send search requests with the same keywords. In fact, we use an array to save the key that has already sent the request and the corresponding data object returned, you can also modify the above js Code as follows:
<Script type = "text/javascript"> $ (function () {var cache ={}; $ ("# txtSearchKey "). autocomplete ({source: function (request, response) {var term = request. term; if (term in cache) {data = cache [term]; response ($. map (data. citylist, function (item) {return {label: item. city, value: item. city }}));} else {$. ajax ({url :" http://demo.com/ajax/Autocomplete.ashx ", DataType:" jsonp ", data: {top: 10, key: term}, success: function (data) {if (data. citylist. length) {cache [term] = data; response ($. map (data. citylist, function (item) {return {label: item. city, value: item. city }})) ;}}}) ;}, select: function (event, ui) {// submit the search ...}, minLength: 2, autoFocus: false, delay: 500}) ;}); </script>
The corresponding server program is as follows:
using System;using System.Web;using AutoCompleteDemo.common;using System.Collections.Generic;using System.Text;namespace AutoCompleteDemo.ajax{ public class Autocomplete : IHttpHandler { public void ProcessRequest(HttpContext context) { string key = TextHelper.DangerStringClear(RequestHelper.GetQueryString("key")); int top = RequestHelper.GetIntQueryString("top", 10); string callback = TextHelper.DangerStringClear(RequestHelper.GetQueryString("callback")) + "({\"citylist\":["; if (!string.IsNullOrEmpty(key)) { City city = new City(); Dictionary<int, string> diclist = city.GetCityName(key, top); if (diclist != null && diclist.Count > 0) { StringBuilder sbJson = new StringBuilder(150); foreach (KeyValuePair<int, string> item in diclist) { sbJson.Append("{\"id\":" + item.Key + ",\"city\":\"" + item.Value + "\"},"); } callback += sbJson.ToString().Length > 0 ? sbJson.ToString().TrimEnd(',') : ""; } } context.Response.Write(callback + "]})"); } public bool IsReusable { get { return false; } } }}
It must be noted that when sending a cross-origin request, a callback parameter is automatically appended (if it is passed through $. getJOSN is jsoncallback) when outputting json data, the callback parameter value must be output; otherwise, the callback function cannot be called.
The final implementation is attached: