In the previous articles about Jquery Select2, Select2 is a jQuery-based alternative selection box. It supports search, remote datasets, and unlimited scrolling results.
We will continue to share with you the usage of Select2 today.
1. Select2 binding event
The event can be used when select data is bound, opened, or closed.
The code is as follows: |
Copy code |
$ ("# Selectsq"). select2 (); $ ("# Selectsq"). on ("change", function (e) {ToggleProductList ();})
|
In the ToggleProductList function, you can determine whether to select the correct data:
The code is as follows: |
Copy code |
Function Getselect2ID (idd ){ Var data = $ ("#" + idd). select2 ("data "); Var datastring = ""; $. Each (data, function (key, val ){ Datastring = datastring + val. id + ","; }); Return datastring; } Function ToggleProductList (){ Var sqlist = Getselect2ID ("selectsq "); If (sqlist. length> 0 ){ $ ("# DivselectProduct"). show (); } Else { $ ("# DivselectProduct"). hide (); } } Var data = $ ("#" + idd). select2 ("data") is used to obtain the data selected by the select statement. |
2. Multiple options are supported.
Similar to the multi-tags selection shown in the preceding figure, you only need to define the attribute multiple = "".
The code is as follows: |
Copy code |
<Select multiple = "" name = "selectsq" id = "selectsq" style = "width: 300px" class = "populate select2-offscreen" tabindex = "-1"> |
3. Dynamically bind data. You can use the method of getting data, organizing html, or using the ajax method that comes with Select2.
The code is as follows: |
Copy code |
Function GetCityData (){ Var cityId = GetCity (); $. Ajax ({ Type: "post ", DataType: 'json ', Url: ajaxUrl, Data :{ Operate: "searchcitydata ", Txtsqname: $ ("# txtsqname"). val (), Txtspname: $ ("# txtspname"). val (), Txtsjname: $ ("# txtsjname"). val (), CityId: cityId }, Success: function (data, textStatus ){ If (data! = Null ){ Var model = eval (data ); If (model! = Null & model! = "Undefined "){ // Selectsq Var html = ''; $. Each (model. ListSQ, function (key, val ){ Html = html + '<option value = "' + val. Id + '">' + val. Name + '</option> '; }); $ ("# Selectsq"). append (html ); } Else { Alert ("failed to load data! "); Return; } } }, Complete: function (XMLHttpRequest, textStatus ){ }, Error: function (e ){ Alert ("loading data error! "); Return; } }); } |