Use JQuery UI Autocomplete

Source: Internet
Author: User

Use JQuery UI Autocomplete
JQuery. Autocomplete is a popular plug-in of jquery. It can automatically complete the input box (autocomplete) and suggest the input suggest function, and supports ajax data loading.
Http://jqueryui.com/autocomplete/

A complete simple example on the official website:

  1. <! Doctype html>
  2. <Html lang = "en">
  3. <Head>
  4. <Meta charset = "UTF-8">
  5. <Title> jQuery UI Autocomplete-Default functionality </title>
  6. <Link rel = "stylesheet" href = "// code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
  7. <Script src = "// code.jquery.com/jquery-1.10.2.js"> </script>
  8. <Script src = "// code.jquery.com/ui/1.11.4/jquery-ui.js"> </script>
  9. <Link rel = "stylesheet" href = "/resources/demos/style.css">
  10. <Script>
  11. $ (Function (){
  12. Var availableTags = [
  13. "ActionScript ",
  14. "AppleScript ",
  15. "Asp ",
  16. "BASIC ",
  17. "C ",
  18. "C ++ ",
  19. "Clojure ",
  20. "COBOL ",
  21. "ColdFusion ",
  22. "Erlang ",
  23. "Fortran ",
  24. "Groovy ",
  25. "Haskell ",
  26. "Java ",
  27. "JavaScript ",
  28. "Lisp ",
  29. "Perl ",
  30. "PHP ",
  31. "Python ",
  32. "Ruby ",
  33. "Scala ",
  34. "Scheme"
  35. ];
  36. $ ("# Tags"). autocomplete ({
  37. Source: availableTags
  38. });
  39. });
  40. </Script>
  41. </Head>
  42. <Body>

  43. <Div class = "ui-widget">
  44. <Label for = "tags"> Tags: </label>
  45. <Input id = "tags">
  46. </Div>


  47. </Body>
  48. </Html>


1. Data Source designation
The main parameter of this function is source. Set the matching menu to match the data items. Setting method:

1. string array parameter. Format: ["Choice1", "Choice2"]
  1. During initialization:
  2. $ (". Selector "). autocomplete ({source: ["c ++", "java", "php", "coldfusion", "javascript", "asp", "ruby"]});


  3. After Initialization
  4. // Getter
  5. Var source = $ (". selector"). autocomplete ("option", "source ");


  6. // Setter
  7. $ (". Selector "). autocomplete ("option", "source", ["c ++", "java", "php", "coldfusion", "javascript", "asp ", "ruby"]);

2. object array parameters, in the format of [{label: "Choice1", value: "value1"},...] label indicates the value of the item displayed in the matching menu, and value indicates the actual value from append to <input> after this matching item is selected.

3. If the string parameter is a string parameter, a remote data source is specified. After the <input> event changes, the data is sent to the remote data source in GET mode. The input content is saved with the term parameter;
For example, if the parameter is http: // remoteSource, a GET request, such as http: // remoteSource? Term = abc
The returned results must be in json format, as described in 1 and 2 above.
Then receive it on the server side and output the corresponding results. Note that the default parameter name is "term:
  1. Public void ProcessRequest (HttpContext context)
  2. {
  3. // The default query parameter name is term.
  4. String query = context. Request. QueryString ["term"];
  5. Context. Response. ContentType = "text/javascript ";
  6. // Output string array or JSON Array
  7. Context. response. write ("[{\" label \ ": \" blog garden \ ", \" value \ ": \" cnblogs \ "}, {\" label \": \ "monthly subscription \", \ "value \": \ "monthly subscription \"}] ");
  8. }

4. The function parameter, in the format of Function (Object request, Function response (Object data), is the most flexible and allows you to issue queries to the server in your own way and parse the data yourself, finally, write the data back to response.
  1. $ (". Selector"). autocomplete ({
  2. Source: function (request, response ){
  3. // Obtain user input
  4. Var term = request. term;
  5. // Obtain data from the server in custom Mode
  6. ...
  7. // You can also parse the data yourself
  8. ..
  9. // Finally, put the data in the response format described in the previous 1 and 2.
  10. Response (data );
  11. }
  12. });
Example:
  1. Var hosts = ["gmail.com", "live.com", "hotmail.com", "yahoo.com", "cnblogs.com", "Mars. com", "yuyue. com"];
  2. $ ("# Email1"). autocomplete ({
  3. AutoFocus: true,
  4. Source: function (request, response ){
  5. Var term = request. term, // request. term is the input string
  6. Ix = term. indexOf ("@"),
  7. Name = term, // User name
  8. Host = "", // Domain Name
  9. Result = []; // result

  10. Result. push (term );
  11. // Result. push ({label: term, value: term}); // json format
  12. If (ix>-1 ){
  13. Name = term. slice (0, ix );
  14. Host = term. slice (ix + 1 );
  15. }
  16. If (name ){
  17. Var findedHosts = (host? $. Grep (hosts, function (value ){
  18. Return value. indexOf (host)>-1;
  19. }): Hosts ),
  20. FindedResults = $. map (findedHosts, function (value ){
  21. Return name + "@" + value; // return string format
  22. // Return {label: name + "@" + value, value: name + "@" + value}; // json format
  23. });
  24. Result = result. concat ($. makeArray (findedResults ));
  25. }
  26. Response (result); // present the result
  27. }
  28. });


Feature 2:
This automatic complementing function supports <input> <textarea> or labels with the contenteditable attribute.

Keyboard operation:
1. You can select matching items for the up and down keys.
2. The matching menu can be disabled by esc.
3. enter to select the currently selected match
4. pageup pagedown can be used to match the scroll bar in the menu.

CSS:
1. ui-autocomplete: matches the css attribute of the matching item in the menu
2. ui-autocomplete-input: attributes of the input box

Dependency:
<Link rel = "stylesheet" href = "http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"/>
<Script src = "http://code.jquery.com/jquery-1.9.1.js"> </script>
<Script src = "http://code.jquery.com/ui/1.10.3/jquery-ui.js"> </script>


Three major events
There are 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:
["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:
  1. // In the Parameter
  2. $ ("# Autocomp"). autocomplete ({
  3. Source: availableTags
  4. , Select: function (e, ui ){
  5. Alert (ui. item. value)
  6. }
  7. });

  8. // Bind
  9. $ ("# Autocomp"). bind ("autocompleteselect", function (e, ui ){
  10. Alert (ui. item. value );
  11. });
The event name used for bind binding is "autocomplete" + event name. For example, "select" is "autocompleteselect ".


Autocomplete with more than four 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, specific can refer to http://www.cnblogs.com/lwme/archive/2012/02/12/jquery-ui-autocomplete.html

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.