Home >Web Front-end >JS Tutorial >jQuery Autocomplete instance introduction

jQuery Autocomplete instance introduction

小云云
小云云Original
2018-01-01 10:27:233416browse

This article mainly introduces an introduction to jQuery Autocomplete. jQuery UI Autocomplete is the autocomplete component of jQuery UI. It is the most powerful and flexible Autocomplete I have ever used. It supports local Array/JSON arrays and Array requests through ajax. /JSON array, JSONP, and Function (the most flexible) methods to obtain data.

jQuery UI Autocomplete is the autocomplete component of jQuery UI. It is the most powerful and flexible Autocomplete I have ever used. It supports local Array/JSON arrays, Array/JSON arrays requested through ajax, and JSONP , and Function (the most flexible) to obtain data.

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:

["bjpowernode","动力节点","李四"]

For Array in JSON format, it is required to have: label and value attributes, as follows:

[{label: "动力节点", value: "bjpowernode"}, {label: "李四", value: "李四"}]

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, use the other attribute instead (that is, value and label have the same value), as follows:

[{label: "bjpowernode"}, {label: "李四"}]
[{value: "bjpowernode"}, {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:

[{"label": "动力节点", "value": "bjpowernode"}, {"label": "李四", "value": "李四"}]

Otherwise, a parsererror error may occur.

Main parameters

The commonly used parameters of jQuery UI Autocomplete are:

1.Source: used to specify the data source, the type is String, Array, Function

  1. String: Server-side address used for ajax request, returns Array/JSON format

  2. Array: String Array or JSON array

  3. Function(request, response): Get the input value through request.term, response([Array]) to present the data; (JSONP is this way)

2.minLength: When the length of the string in the input box reaches minLength, activate Autocomplete

3.autoFocus: When the Autocomplete selection menu pops up, automatically select The first

4.delay: that is, how many milliseconds to delay to activate Autocomplete

Other less commonly used ones will not be listed.

How to use

If there is the following input box on the page:

<input type="text" id="autocomp" />

AJAX request
By specifying the source as the server-side address To implement, 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 passed parameter name is term:

public void ProcessRequest(HttpContext context) {   
// 查询的参数名称默认为term   
string query = context.Request.QueryString["term"];   
context.Response.ContentType = "text/javascript";   
//输出字符串数组 或者 JSON 数组   
context.Response.Write("[{\"label\":\"动力节点\",\"value\":\"bjpowernode\"},{\"label\":\"李四\",\"value\":\"李四\"}]"); }

Local Array/JSON array

// 本地字符串数组
var availableTags = [
  "C#",
  "C++",
  "Java",
  "JavaScript",
  "ASP",
  "ASP.NET",
  "JSP",
  "PHP",
  "Python",
  "Ruby"
];
$("#local1").autocomplete({
  source: availableTags
});
// 本地json数组
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

Obtain custom data by specifying the source as a custom function. The function mainly has two parameters (request, response), respectively. Used to obtain input values ​​and present results

Local Array method to obtain data (imitating Sina Weibo login)

var hosts = ["gmail.com", "live.com", "hotmail.com", "yahoo.com", "bjpowernode.com", "火星.com", "李四.com"];
$("#email1").autocomplete({
  autoFocus: true,
  source: function(request, response) {
    var term = request.term, //request.term为输入的字符串
      ix = term.indexOf("@"),
      name = term, // 用户名
      host = "", // 域名
      result = []; // 结果
 
    result.push(term);
    // result.push({ label: term, value: term }); // json格式
    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 { label: name + " @ " + value, value: name + "@" + value }; // json格式
      });
      result = result.concat($.makeArray(findedResults));
    }
    response(result);//呈现结果
  }
});

JSONP method to obtain data

Taken directly from the official DEMO, send an ajax request to the remote server, then process the return result, and finally present it through response:

$("#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:

1.create(event, ui): When Autocomplete is created, you can in this event, Have some control over the appearance

2.search(event, ui): Before starting the request, you can return false in this event to cancel the request

3.open (event, ui): When the Autocomplete result list pops up

4.focus(event, ui): When any item in the Autocomplete result list gets focus, ui.item is the item that gets the focus

5.select(event, ui): When any item in the Autocomplete result list is selected, ui.item is the selected item

6.close(event, ui ): When the Autocomplete result list is closed

7.change(event, ui): When the value changes, ui.item is the selected item

The events of these events The item attribute of the ui parameter (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, there are three types:

["bjpowernode","动力节点","李四"]
[{label: "动力节点", value: "bjpowernode"}, {label: "李四", value: "李四"}]
[{label: "动力节点", value: "bjpowernode", id: "1"}, {label: "李四", value: "李四", id: "2"}]

If it is the third type If so, you can also get the value of ui.item.id.

These events can be bound in 2 ways, as follows:

// 在参数中
$("#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 to bind through bind is "autocomplete" + 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 to bind some events for additional processing:

1. Return false in the focus event to prevent the value of the input box from being replaced by a single value of autocomplete

2. Combine multiple values ​​in the select event

3. Do some processing in the keydown event of the element, the reason is the same as 1

4. Use the callback function source to get the last input value and present the result

Or just take the official DEMO code directly:

// 按逗号分隔多个值
function split(val) {
  return val.split(/,\s*/);
}
// 提取输入的最后一个值
function extractLast(term) {
  return split(term).pop();
}
// 按Tab键时,取消为输入框设置value
function keyDown(event) {
  if (event.keyCode === $.ui.keyCode.TAB &&
      $(this).data("autocomplete").menu.active) {
    event.preventDefault();
  }
}
var options = {
  // 获得焦点
  focus: function() {
    // prevent value inserted on focus
    return false;
  },
  // 从autocomplete弹出菜单选择一个值时,加到输入框最后,并以逗号分隔
  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;
  }
};
// 多个值,本地数组
$("#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)));
    }
  }));
// 多个值,ajax返回json
$("#ajax3").bind("keydown", keyDown)
  .autocomplete($.extend(options, {
    minLength: 2,
    source: function(request, response) {
      $.getJSON("remoteJSON.ashx", {
        term: extractLast(request.term)
      }, response);
    }
  }));

Related recommendations:

How to use autocomplete in Ionic3 UI components

Recommend 10 commonly used AutoComplete example usages, welcome to download!

AutoComplete usage summary

The above is the detailed content of jQuery Autocomplete instance introduction. For more information, please follow other related articles on the PHP Chinese website!

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