Describes how to use the jQuery autoComplete plugin and how to dynamically change the parameter value.

Source: Internet
Author: User

Describes how to use the jQuery autoComplete plugin and how to dynamically change the parameter value.

This document describes how to use the jQuery autoComplete plug-in and how to dynamically change the parameter value. We will share this with you for your reference. The details are as follows:

I. One-time loading and multiple use:

Front-end JS Code:

/* Automatically match the customer name */function customerAutoComplete () {$. ajax ({type: "GET", url: encodeURI ("/approvalajax/salesOrderApproval_findCustomerList"), dataType: "json", success: function (data, textStatus) {if (data! = Null & data. customerList! = Null) {$ ("# customerFullName "). autocomplete (data. customerList, {/** add custom header **/tableHead: "<div> <span style = 'width: 40% 'class = 'col-1'> Customer Code </span> <span style = 'width: 58% 'class = 'col-2'> customer name </span> </div> ", minChars: 0, width: 310, matchContains:" true ", autoFill: false, extraParams: {ledger: $ ("# ledger "). val ()}, formatItem: function (row, I, max) {return "<span style = 'width: 40% 'class = 'col-1'>" + row. cusCode + "</span>" + "<span style = 'width: 58% 'class = 'col-2'>" + row. cusName + "</span>" ;}, formatMatch: function (row, I, max) {return row. cusCode + row. cusName;}, formatResult: function (row) {return row. cusName ;}}). result (function (e, data, value, sec) {/** Add the selected callback function **/clearCustomerInfo (); $ ("# customerShortName "). val (data. cusAbbName); $ ("# customerFullName "). val (data. cusName); $ ("# customerCode "). val (data. cusCode);/* load the corresponding product line, payment and receipt agreement, billing period */setPLAndPCAndCP (data. cusCode);/* load inventory Code */setInventoryAutoComplete (data. cusCode );}). bind ("unmatch", function () {clearCustomerInfo ();});}}});}

Background JAVA code:

/*** Asynchronous request result. */private Map <String, Object> ajaxResultMap;/*** @ Description asynchronously loads the customer list according to the account set * @ throws Exception * @ return String */public String findCustomerList () throws Exception {ajaxResultMap = new HashMap <String, Object> (); response. setContentType ("text/html; charset = UTF-8"); response. setCharacterEncoding ("UTF-8"); List <ErpCustomer> list = erpDataService. findCustomerList (ledger); ajaxResultMap. put ("customerList", list); return SUCCESS ;}

Configuration File Code:

<Package name = "approval-ajax" extends = "json-default" namespace = "/approvalajax"> <! -- Sales order approval --> <action name = "salesOrderApproval _ *" method = "{1}" class = "xx. xxx. xxAction "> <result type =" json "> <param name =" root "> ajaxResultMap </param> <param name =" contentType "> text/html </param> </result> </action> </package>

Ii. Dynamic Loading based on input content:

Front-end JS Code:

/* Automatically match the customer name */function customerAutoComplete () {$ ("# customerFullName "). autocomplete (encodeURI ("/approvalajax/salesOrderApproval_findCustomerList"), {/** add custom header **/tableHead: "<div> <span style = 'width: 40% 'class = 'col-1'> Customer Code </span> <span style = 'width: 58% 'class = 'col-2'> customer name </span> </div> ", minChars: 0, width: 310, matchContains:" true ", autoFill: false, extraParams: {ledger: $ ("# ledger "). val ()}, dataType: 'json', parse: function (data) {var rows = []; if (data = null | data. customerList = null) {return rows;} for (var I = 0; I <data. customerList. length; I ++) {rows [rows. length] = {data: data. customerList [I], // the data format value: data is displayed in the drop-down list. customerList [I]. cusName, // the actual data format after selection result: data. customerList [I]. cusName // After selection, the input box displays the data format };} return rows ;}, formatItem: function (row, I, max) {return "<span style = 'width: 40% 'class = 'col-1'> "+ row. cusCode + "</span>" + "<span style = 'width: 58% 'class = 'col-2'>" + row. cusName + "</span>" ;}, formatMatch: function (row, I, max) {return row. cusCode + row. cusName;}, formatResult: function (row) {return row. cusName ;}}). result (function (e, data, value, sec) {/** Add the selected callback function **/clearCustomerInfo (); $ ("# customerShortName "). val (data. cusAbbName); $ ("# customerFullName "). val (data. cusName); $ ("# customerCode "). val (data. cusCode); $ ("# licensecode "). val (data. licensecode);/* load the corresponding product line, payment and receipt agreement, billing period */setPLAndPCAndCP (data. cusCode);/* inventory Code */addInventoryAutoComplete ($ ("# detailListTbody "). find ("input [tdTag = inventoryCode]");}). bind ("unmatch", function () {clearCustomerInfo ();});}

Background JAVA code:

/*** @ Fields q automatically fills in the auxiliary character */private String q;/*** asynchronous request result. */private Map <String, Object> ajaxResultMap;/*** @ Description asynchronously loads the customer list according to the account set * @ throws Exception * @ return String */public String findCustomerList () throws Exception {ajaxResultMap = new HashMap <String, Object> (); response. setContentType ("text/html; charset = UTF-8"); response. setCharacterEncoding ("UTF-8"); List <ErpCustomer> list = erpDataService. findTop5CustomerList (ledger, q); ajaxResultMap. put ("customerList", list); return SUCCESS ;}

Note:When dynamic loading is used, the plug-in the request URL will automatically append the q Parameter to transmit the input parameter.

Note: When you use the autoComplete plug-in Jquery to implement automatic matching, an error message is displayed when you use it directly to parse the json object, because it uses "/n" to split rows and "|" to split fields by default. If you need to use it to parse json objects, You need to implement its own parse method.

Parameter description:

* MinChars (Number ):
The number of characters that the user must enter before triggering autoComplete. Default: 1. If it is set to 0, double-click the input box or delete the content in the input box to display the list.
* Width (Number ):
Width of the drop-down box. Default: width of the input element
* Max (Number ):
AutoComplete drop-down shows the number of projects. Default: 10
* Delay (Number ):
The delay time (in milliseconds) for activating autoComplete after the key is clicked. Default: the remote value is 400 local 10
* AutoFill (Boolean ):
Do you want to automatically enter the user's current mouse value in the input box when the user selects it? Default: false
* MustMatch (Booolean ):
If it is set to true, autoComplete will only allow matching results to appear in the input box. If the user inputs illegal characters, the drop-down box will not be available. Default: false
* MatchContains (Boolean ):
Determine whether to check the match within the string during comparison, for example, whether ba matches the ba in foo bar. It is important to use cache. Do not mix it with autofill. Default: false
* SelectFirst (Boolean ):
If it is set to true, the first value of the autoComplete drop-down list is automatically selected when you type the tab or return key, although it is not manually selected (with a keyboard or mouse ). of course, if you select a project, you can use the selected value. default: true
* CacheLength (Number ):
The cache length, that is, the number of records to be cached in the result set obtained from the database. set to 1 as not cached. Default: 10
* MatchSubset (Boolean ):
AutoComplete can be used to cache server queries. If the query result of foo is cached, you do not need to retrieve foo if you enter foo. this option is usually enabled to reduce the burden on the server and improve performance. it is valid only when the cache length is greater than 1. default: true
* MatchCase (Boolean ):
Whether the case sensitivity switch is enabled for comparison. it is important to use the cache. if you understand the previous option, this is not difficult to understand, just like whether foot needs to be searched in the FOO cache. default: false
* Multiple (Boolean ):
Whether multiple values can be input. That is, multiple autoComplete values can be used to input multiple values. Default: false
* MultipleSeparator (String ):
If multiple characters are selected, they are used to separate the selected characters. Default :","
* Scroll (Boolean ):
Whether to use Scroll display when the result set is larger than the Default height Default: true
* ScrollHeight (Number ):
The scroll height of the Automatic completion prompt is expressed in pixels by Default: 180
* FormatItem (Function ):
Use advanced labels for each project to be displayed. this function is called for each row in the result. The returned value is contained in the LI element and displayed in the drop-down list. autocompleter will provide three parameters (row, I, max): The returned result array, the number of rows processed currently (that is, the number of items, which is a natural number starting from 1 ), the number of elements in the current result array is the number of items. default: none, indicating that no custom processing function is specified, so that each row in the drop-down list contains only one value.
* FormatResult (Function ):
Similar to formatItem, You Can format the value to be entered in the input text box. there are also three parameters, the same as formatItem. default: none, which indicates either data only or the value provided by formatItem.
* FormatMatch (Function ):
Use this function to format the data format to be queried for each row of data. The return value is used by the internal search algorithm. The parameter value row
* ExtraParams (Object ):
Provides more parameters for the backend (generally server scripts. like the common practice, a key-Value Pair object is used. if the passed value is {bar: 4}, it will be parsed into my_autocomplete_backend.php by autocompleter? Q = foo & bar = 4 (assuming the current user has entered foo). Default :{}
* Result (handler) Returns: jQuery
This event is triggered after you select an item. The parameter is:
Event: event object. event. type is result.
Data: The selected data row.
Formatted: value returned by the formatResult Function
For example:

$ ("# SingleBirdRemote"). result (function (event, data, formatted) {// assign values to other controls after selection, trigger other events, etc });

Note:Another way is to dynamically change the parameter input value.

We know that this plug-in has an extraParams parameter, because jquery. autoComplete only supports the q and limit parameters. In this case, we need to submit more parameters to the server. Fortunately, the author provides us with an extension parameter extraParams. ExtraParams is good, but unfortunately it is a dead parameter. Sometimes, we need to submit a live parameter to the server. For example, we have an automatic completion function of the company name, but we also need to provide the parameters of a city to the server. Normally, there is no problem. However, when the name of a city is selected by the user, the name of the city changes in real time according to the user's selection. At this time, the existing jquery. autoComplete is powerless.

At this time, we should consider modifying jquery. autoComplete. Let's take a look at the code first. The Code has an onChange event, which is a release event. We can add a callback function here to solve the problem. First, we need to add a parameter named onBegin to options, which is about 400 lines. There is a line of code like this:

$.Autocompleter.defaults =

We will add a section later

onBegin: null,

Then we locate the onChange event, which is about 226 lines. The Code is as follows:

function onChange(crap, skipPrevCheck)

Add the following code to the function:

If (options. onBegin ){
Var op = options. onBegin (options );
If (op ){
$. Extend (options, op );
}
}

After the code is modified, it looks like this:

Function onChange (crap, skipPrevCheck) {// 2010-01-27, add the onBegin function, so that when onChange is started, you can reset options if (options. onBegin) {var op = options. onBegin (options); if (op) {$. extend (options, op) ;}// end if (lastKeyPressCode = KEY. DEL) {select. hide (); return;} var currentValue = $ input. val (); if (! SkipPrevCheck & currentValue = previusvalue) return; previusvalue = currentValue; currentValue = lastWord (currentValue); if (currentValue. length> = options. minChars) {$ input. addClass (options. loadingClass); if (! Options. matchCase) currentValue = currentValue. toLowerCase (); request (currentValue, receiveData, hideResultsNow);} else {stopLoading (); select. hide ();}};

Let's look at the call:

/* Automatically match the customer name */function customerAutoComplete () {$ ("# customerFullName "). autocomplete (encodeURI ("/approvalajax/salesOrderApproval_findCustomerList"), {/** add custom header **/tableHead: "<div> <span style = 'width: 40% 'class = 'col-1'> Customer Code </span> <span style = 'width: 58% 'class = 'col-2'> customer name </span> </div> ", minChars: 0, width: 310, multiple: false, mustMatch: false, matchContains: false, matchSubset: false, autoFill: false, onBegin: function (options) {// modify -- used to dynamically change the value options of ledger. extraParams. ledger = $ ("# ledger "). val (); return options ;}, // extraParams: {ledger :$ ("# ledger "). val ()}, dataType: 'json', parse: function (data) {var rows = []; if (data = null | data. customerList = null) {return rows;} for (var I = 0; I <data. customerList. length; I ++) {rows [rows. length] = {data: data. customerList [I], // the data format value: data is displayed in the drop-down list. customerList [I]. cusName, // the actual data format after selection result: data. customerList [I]. cusName // After selection, the input box displays the data format };} return rows ;}, formatItem: function (row, I, max) {return "<span style = 'width: 40% 'class = 'col-1'> "+ row. cusCode + "</span>" + "<span style = 'width: 58% 'class = 'col-2'>" + row. cusName + "</span>" ;}, formatMatch: function (row, I, max) {return row. cusCode + row. cusName;}, formatResult: function (row) {return row. cusName ;}}). result (function (e, data, value, sec) {/** Add the selected callback function **/clearCustomerInfo (); $ ("# customerShortName "). val (data. cusAbbName); $ ("# customerFullName "). val (data. cusName); $ ("# customerCode "). val (data. cusCode); $ ("# licensecode "). val (data. licensecode);/* load the corresponding product line, payment and receipt agreement, billing period */setPLAndPCAndCP (data. cusCode );}). bind ("unmatch", function () {clearCustomerInfo ();});}

In fact, there are only three steps:

1. Add an onBegin parameter to options.
2. In onChange, determine whether onBegin has a value assignment. If so, call this function and return the result of merging the returned values into options.
3. Add some business logic in the onBegin function during the call, and you can reset options.

In this way, we can not only dynamically Add the extraParams parameter, but also dynamically modify other options parameters. This onBegin will be triggered when you change the value of the input box.

Related Article

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.