JQuery AutoComplete plug-in two ways to use and dynamic change of parameter value method _jquery

Source: Internet
Author: User
Tags extend

This article illustrates the two ways of using jquery AutoComplete plug-in and the method of changing parameter values dynamically. Share to everyone for your reference, specific as follows:

一、一次 loading, multiple use:

Front-end JS code:

/* Customer Name Auto-match/function Customerautocomplete () {$.ajax ({type: "Get", Url:encodeuri ("/approvalajax/salesorderappro Val_findcustomerlist "), DataType:" JSON ", success:function (data, Textstatus) {if (data!= null && data
          . customerlist!= null) {$ ("#customerFullName"). AutoComplete (Data.customerlist, {/** Plus 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:" tr  UE ", Autofill:false, Extraparams: {ledger:$ (" #ledger "). Val ()}, formatitem:function (row, I, Max) {return "<span style= ' width:40% ' class= ' col-1 ' >" + row.cuscode + "</span>" + "<span sty
          Le= ' 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) {/**-checked callback functions **/clearcustomerinfo ();
          $ ("#customerShortName"). Val (Data.cusabbname);
          $ ("#customerFullName"). Val (Data.cusname);
          $ ("#customerCode"). Val (Data.cuscode);
          * * According to the choice of customers, account sets load corresponding product line, payment agreement, account period * * SETPLANDPCANDCP (Data.cuscode);
        * * Loading Inventory code/Setinventoryautocomplete (Data.cuscode);
        }. Bind ("Unmatch", function () {clearcustomerinfo ();
      });
}
    }
  });

 }

Background Java code:

/**
 * Asynchronous request result.
 *
private map<string, object> Ajaxresultmap;
/**
 * @Description The customer list is asynchronously loaded 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-related code:

<package name= "Approval-ajax" extends= "Json-default" namespace= "/approvalajax" >
    <!--sales order approval related-->
    <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>

Second, according to the input content dynamic loading:

Front-end JS code:

/* Customer Name Auto-match/function Customerautocomplete () {$ ("#customerFullName"). AutoComplete (encodeURI ("/approvalajax/ Salesorderapproval_findcustomerlist "), {/** Add custom header **/tablehead: <div><span style= ' width:40% ' class= '
    -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: ' J
      Son ', 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//dropdown box displays the data format value:data.customerlist[i].cusname,//The actual data format after selection Result:data.customerlist[i].cus
      Name//Select the input box to display 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 + ' &L
    T;/span> ";
    }, Formatmatch:function (row, I, max) {return row.cuscode+row.cusname;
    }, Formatresult:function (row) {return row.cusname;
    }). result (function (e,data,value,sec) {/**-checked callback functions **/clearcustomerinfo ();
    $ ("#customerShortName"). Val (Data.cusabbname);
    $ ("#customerFullName"). Val (Data.cusname);
    $ ("#customerCode"). Val (Data.cuscode);
    $ ("#licensecode"). Val (Data.licensecode);
    * * According to the choice of customers, account sets load corresponding product line, payment agreement, account period * * SETPLANDPCANDCP (Data.cuscode);
  * * Inventory code/Addinventoryautocomplete ($ ("#detailListTbody"). Find ("Input[tdtag=inventorycode]");
  }. Bind ("Unmatch", function () {clearcustomerinfo ();
});

 }

Background Java code:

/**
 * @Fields Q automatically fills the auxiliary character
 *
/private String Q;
/**
 * Asynchronous request result.
 *
private map<string, object> Ajaxresultmap;
/**
 * @Description The customer list is asynchronously loaded 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 using dynamic loading, the plug-in in the requested URL automatically appends the Q parameter to the input parameters.

Note: When using the AutoComplete plug-in in jquery to implement the automatic matching feature, an error message appears when you use it directly to parse the JSON object because it defaults to the "/n" Split, "|" Split the field. If you need to use it to parse a JSON object, you need to implement its Parse method yourself.

Parameter description:

* Minchars (number):
The number of characters that the user needs to enter at least before triggering the AutoComplete. Default:1, if set to 0, double click in the input box or delete the contents of the input box to display the list
* Width (number):
Specifies the width of the Drop-down box. Width of default:input element
* MAX (number):
AutoComplete Drop-down Displays the number of items. default:10
* Delay (number):
The delay time (in milliseconds) to activate AutoComplete after a keystroke. Default: Remote for 400 local 10
* AutoFill (Boolean):
To automatically fill the input box with the value of the user's current mouse when the user chooses. Default:false
* Mustmatch (Booolean):
If set to True,autocomplete will only allow matching results to appear in the input box, all when the user entered an illegal character will not get the Drop-down box. Default:false
* Matchcontains (Boolean):
Determines whether a match is to be viewed inside a string when comparing, such as whether BA matches the BA in Foo Bar. It is important to use caching. Don't mix with autofill. Default:false
* Selectfirst (Boolean):
If set to True, the first value of the AutoComplete drop-down list is automatically selected when the user types the tab or return key, although it is not manually selected (with the keyboard or mouse). Of course, if a user selects an item, the user selects the value. Default:true
* Cachelength (number):
The length of the cache. That is, how many records to cache for a result set fetched from the database. Set to 1 is not cached. default:10
* Matchsubset (Boolean):
AutoComplete can you use caching for server queries, and if you cache query results for Foo, you don't need to retrieve them if you enter Foo? Use caching directly. This option is usually turned on to reduce the burden on the server to improve performance. will only be valid if the cache length is greater than 1 o'clock. Default:true
* MatchCase (Boolean):
Compare whether the case sensitive switch is turned on. It is important to use caching. If you understand an option, this is not difficult to understand, just like foot to the cache of Foo. Default:false
* Multiple (Boolean):
Whether to allow multiple values to be entered is to use AutoComplete multiple times to enter multiple values. Default:false
* Multipleseparator (String):
When multiple selections are used, separate the characters from each selection. Default: ","
* Scroll (Boolean):
Whether the scroll display is used when the result set is greater than the default height default:true
* ScrollHeight (number):
The scroll height of the auto completion prompt is expressed in pixel size default:180
* Formatitem (Function):
Use the advanced label for each item you want to display. This function is called for each row in the result, and the return value is displayed in the Drop-down list with the LI element. Autocompleter will provide three parameters (row, I, max): The returned array of results, the number of rows currently processed (that is, the first few items, the natural number starting from 1), and the number of the current result array elements, which is the number of items. Default:none, which means that no custom handler function is specified, so that each row in the Drop-down list contains only one value.
* FormatResult (Function):
Similar to Formatitem, but you can format the values that you want to enter into the input text box. There are also three parameters, like Formatitem. Default:none, which means either only data, or values supplied with Formatitem.
* Formatmatch (Function):
Use this function for each row of data to format the data that you want to query. The return value is used for the internal search algorithm. Parameter Value row
* Extraparams (Object):
Provides additional parameters for the background (typically the server-side script). As is often the case, a key value pair object is used. If the pass value is {Bar:4}, it will be autocompleter parsed into My_autocomplete_backend.php?q=foo &bar=4 (assuming the current user has entered Foo). Default: {}
* Result (handler) Returns:jquery
This event is triggered when a user selects an item, and the parameter is:
Event: Events object. Event.type for result.
Data: Selected rows.
Value returned by the Formatted:formatresult function
For example:

$ ("#singleBirdRemote"). Result (function (event, data, formatted) {
 //such as assigning values to other controls after selection, triggering other events, and so on
});

Note: Another way to dynamically change the parameters passed in values.

We know that this plugin has a extraparams parameter, Because Jquery.autocomplete only supports Q and limit two parameters, if there is such a situation, we need to submit more parameters to the server how to do it, fortunately, the author provides us with an extended parameter, is the Extraparams. Extraparams good is good, but unfortunately, it is a dead parameter, and sometimes we need to submit a live parameter to the server. For example, for example, we have a company name AutoComplete, but we also need to provide the server with a city parameters, the normal situation is not a problem. But when the name of the city is chosen by the user, there is a problem, also said that the city's name is based on user choice and real-time changes, this time, the existing jquery.autocomplete can do nothing.

This time we need to consider the modification of the Jquery.autocomplete, we first look at the code, the code has a onchange event, this is a solution, we can add a callback function here to solve the problem. First we have to add a parameter to the options called Onbegin, roughly 400 lines or so, there is a line of code like this:

$. Autocompleter.defaults =

We'll add a paragraph later

Onbegin:null,

Then we find the onchange event, about 226 lines, and the code is as follows:

function OnChange (crap, Skipprevcheck)

Add the following code inside the function:

if (Options.onbegin) {
var op = options.onbegin (options);
if (OP) {
$.extend (options, OP);
}
}

This code looks like this after it's been modified:

function OnChange (crap, Skipprevcheck) {
    //2010-01-27, add a onbegin function so that when you start OnChange, you can reset the 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 = = previousvalue) return
      ;
    Previousvalue = 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 ();
    }
;

Then look at the call:

/* Customer Name Auto-match/function Customerautocomplete () {$ ("#customerFullName"). AutoComplete (encodeURI ("/approvalajax/ Salesorderapproval_findcustomerlist "), {/** Add custom header **/tablehead: <div><span style= ' width:40% ' class= '
    -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:fal
      SE, onbegin:function (options) {//modify--for dynamically changing ledger value options.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 ],//dropdown box display data format VALUE:DATA.CUSTOMERLIST[I].CUSNAME,//Selected after the actual data format Result:data.customerlist[i].cusname//Selected after the input box display data format};
    } return rows; }, Formatitem:function (row, I, max) {return "<span style= ' width:40% ' class= ' col-1 ' >" + row.cuscode + "&L
    T;/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) {/**-checked callback functions **/clearcustomerinfo ();
    $ ("#customerShortName"). Val (Data.cusabbname);
    $ ("#customerFullName"). Val (Data.cusname);
    $ ("#customerCode"). Val (Data.cuscode);
    $ ("#licensecode"). Val (Data.licensecode);
  * * According to the choice of customers, account sets load corresponding product line, payment agreement, account period * * SETPLANDPCANDCP (Data.cuscode);
  }. Bind ("Unmatch", function () {clearcustomerinfo ();
});

 }

In fact, there are only three steps to do:

1. Add a onbegin parameter to the options
2. In the onchange to determine whether the Onbegin is assigned, if so, call this function, return the return value merged into the options
3. When called, add some business logic to the Onbegin function and reset the options

In this way, we can not only achieve dynamic to add extraparams parameters, but also can dynamically modify other options parameters, this onbegin when the user changes the value of the input box will be triggered.

More interested readers of jquery-related content can view the site topics: "jquery window Operation tips Summary", "jquery drag and drop effects and tips summary", "jquery common Plug-ins and Usage summary", "jquery Ajax Usage Summary", "jquery Table" ( Table) Summary of operations tips, jquery Extended techniques Summary, jquery Common Classic effects summary, jquery animation and special effects usage summary and jquery selector Usage Summary

I hope this article will help you with the jquery program design.

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.