Metronic_ drop-down list Select2 plug-in usage

Source: Internet
Author: User
Tags list of attributes

This plugin is a select-based extension that provides richer functionality and user experience, and its GitHub website address is: https://select2.github.io/, the specific use case, can refer to address: https:// Select2.github.io/examples.html.

Throughout the framework, we have used a lot of Select2 controls to handle the display of content, including the selection of drop-down lists (including cascading selection boxes), check drop-down lists, tree drop-down lists, and so on, as shown below.

1) The editing interface of the provinces, cities, the administrative region of the Cascade interface effect, select the province, will load the city under the corresponding provinces, select the city, will continue to load the city's administrative districts, so as to achieve a multi-level associated drop-down list effect.

2) Multiple selection drop-down list under Edit interface

But when we select the content, the system automatically displays the list data that is not selected, which is very intuitive and friendly, as shown below.

3) drop-down list of tree-shaped list

Sometimes, some of our data may be hierarchical, such as the organization, top-level lists, and so on.

2. Actual use code analysis of SELECT2 control 1) Basic interface code and Operation

Use the Select2 control, which is typically set on a regular select control (set its class to Select2).

<div class= "col-md-6" >    <div class= "Form-group" >        <label class= "Control-label col-md-4" > Important levels </label>        <div class= "col-md-8" >            select2"placeholder=" important levels ... "></select >        </div>    </div></div> <div class= "col-md-6" >    <div class= "Form-group" >        <label class= "Control-label col-md-4" > Recognition level </label>        <div class= "col-md-8" >            select2"placeholder=" recognition degree ... "></select>        </div>    </div></div>

If it is a fixed list, then it is set to its option content, as shown below.

<div class= "col-md-6" >    <div class= "Form-group" >        <label class= "Control-label col-md-4" > Smoking </label>        <div class= "col-md-8" >            <select id= "smoking" name= "smoking" type= "text" class= " Form-control select2 "placeholder=" smoking ... ">                <option> smoking </option>                <option> non-smoking </ option>            </select>        </div>    </div></div>

The simple Select2 control initialization code is shown below.

$ (document). Ready (function () {  $ (". Js-example-basic-single"). Select2 ();});

In general, if you allow multiple items to be checked, then set multiple= "multiple", as shown in the following code.

<select id= "Responsedemand" name= "Responsedemand" multiple= "multiple" class= "Form-control select2" ></ Select>
2) asynchronous data-binding operations

In general, the data for our select control is dynamically loaded from the database, so it is generally possible to get the data and bind it in AJAX mode.

Based on the consideration of code reusability, we write a common JS function to reduce the code of the binding operation and improve the reusability of code.

Binds the dictionary contents to the specified Select control function bindselect (ctrlname, url) {    var control = $ (' # ' + ctrlname);    Set SELECT2 processing    control.select2 ({        allowclear:true,        formatresult:formatresult,        formatselection: Formatselection,        escapemarkup:function (m) {            return m;        }    });    Binding Ajax content    $.getjson (URL, function (data) {        control.empty ();//Empty drop-down box        $.each (data, function (I, item) {            control.append ("<option value=" + Item. Value + "' >&nbsp;" + item. Text + "</option>");});}    );

In this way, the data that binds the common dictionary module can be further encapsulated by the following process.

Binds the dictionary contents to the specified control function Binddictitem (Ctrlname, dicttypename) {    var url = '/dictdata/getdictjson?dicttypename= ' + encodeURI (dicttypename);    Bindselect (ctrlname, URL);}

This allows us to initialize the Select2 control and dynamically bind the corresponding dictionary value or other data, which can be implemented by the following initialization code. Where Binddictitem is directly bound to the contents of the dictionary, Bindselect is to obtain and bind data based on the URL, and $ ("#Province"). On ("Change", function (e) {}); is to deal with the selection of changes in the linkage operation.

        Initialize dictionary information (drop-down list) function Initdictitem () {//Partial assignment Reference Binddictitem ("area", "City            field zoning ");            Binddictitem ("Industry", "customer industry");            Binddictitem ("Grade", "Customer Level");            Binddictitem ("CustomerType", "Customer Type");            Binddictitem ("source", "Customer Source");            Binddictitem ("Creditstatus", "credit rating");            Binddictitem ("Stage", "Customer phase");            Binddictitem ("Status", "Customer State");                             Binddictitem ("Importance", "important level");            Binding provinces, cities, administrative regions (linkage processing) bindselect ("Province", "/province/getallprovincenamedictjson");                $ ("#Province"). On ("Change", function (e) {var provincename = $ ("#Province"). Val ();            Bindselect ("City", "/city/getcitysbyprovincenamedictjson?provincename=" + provincename);            });                $ ("#City"). On ("Change", function (e) {var cityname = $ ("#City"). Val (); Bindselect ("District", "/district/getdistrictbyCitynamedictjson?cityname= "+ cityname);        }); }

While the MVC controller returns the data, we are returning a JSON data list to the front page, with their data format as shown below.

[{"Text": "", "Value": "}, {" text ":" Academic Meeting "," value ":" Academic Meeting "}, {" text ":" Friend Introduction "," Value ":" Friend Introduction "}, {" text ":" Advertising Media ", "Value": "Advertising Media"}]

When the front-end page is bound to the Select2 control, the properties of the JSON object are used.

    Binding Ajax content    $.getjson (URL, function (data) {        control.empty ();//Empty drop-down box        $.each (data, function (I, item) {            control.append ("<option value=" + Item.  + "' >&nbsp;" + item. Text + "</option>");})    ;

The implementation code for the controller is as follows:

        <summary>///////Dictionary data is available for the UI control///</summary>//        <param name= "Dicttypename > Dictionary type name </param>        //<returns></returns> public ActionResult Getdictjson (string Dicttypename)        {            list<clistitem> treelist = new list<clistitem> ();            Clistitem pnode = new Clistitem ("", "");            Treelist.insert (0, pnode);            dictionary<string, string> dict = Bllfactory<dictdata>. Instance.getdictbydicttype (dicttypename);            foreach (String key in Dict. Keys)            {                treelist.add (new Clistitem (Key, Dict[key]));            }            Return tojsoncontent (treelist);        }
3) A tree-shaped list of binding operations

For a list of attributes, such as hierarchical data for the owning company, the owning department, and so on, its binding operations are similar, as shown in the following code.

            Binding add-on interface of the company, department, direct manager            Bindselect ("company_id", "/user/getmycompanydictjson?userid=" [email protected]["UserId"] );            $ ("#Company_ID"). On ("Change", function (e) {                var CompanyID = $ ("#Company_ID"). Val ();                Bindselect ("dept_id", "/user/getdeptdictjson?parentid=" + CompanyID);            });            $ ("#Dept_ID"). On ("Change", function (e) {                var DeptID = $ ("#Dept_ID"). Val ();                Bindselect ("PID", "/user/getuserdictjson?deptid=" + DeptID);            });

Just the data they return, we use it as indented display.

[{"Text": "Echidi Group", "Value": "1"}, {"Text": "Guangzhou Branch", "Value": "3"}, {"text": "Shanghai Branch", "Value": "4"}, {"Text": "North Beijing branch "," Value ":" 5 "}]

Or as shown below

[{"Text": "Guangzhou Branch", "Value": "3"}, {"Text": "General manager", "Value": "6"}, {"Text": "Finance Department", "Value": "7"}, {"Text": "Engineering department", "V  Alue ":" 8 "}, {" Text ":" Product Development Department "," Value ":" 9 "}, {" text ":" Develop a set "," Value ":" + "}, {" Text ":" Development Two Group "," Value ":" 15 "}, {"Text": "Test Group", "value": "+"}, {"Text": "Market department", "value": "Ten"}, {"Text": "Market part", "Value": "Max"}, {"Text": "City Field two "," Value ":" ""}, {"text": "Integrated", "value": "One"}, {"Text": "Production", "Value": "" "}, {" Text ":" Human Resources department "," value ":" 13 " } ]

In the two parts, we can see the content of their text, which is based on the hierarchical relationship of the space increase, so as to achieve a hierarchical relationship display.

But from this interface effect, this kind of processing really does not have easyui inside, to the drop-down list tree's display looks good, perhaps may use the better bootstrap plugin to carry on this tree shape content display.

4) Assignment handling of Select2 controls

The method described above is to introduce the initialization of the Select2 control, binding related data, then if we initialize the interface, when we bind the value of the editing interface, we need to assign the value to the control, let it show the real need to display the item.

The method of emptying the control is as follows.

            Empties the value of the Select2 control by            $ ("#PID"). Select2 ("Val", "");            $ ("#Company_ID"). Select2 ("Val", "");            $ ("#Dept_ID"). Select2 ("Val", "");

If you need to purge for more than one control, you can use the collection for processing

            var Select2ctrl = ["Area", "Industry", "Grade", "CustomerType", "Source", "Creditstatus", "Stage", "Status", "importance" ];            $.each (Select2ctrl, function (I, item) {                var ctrl = $ ("#" + Item);                Ctrl.select2 ("Val", "");            });

Assign a value to the Select2 control so that it displays the item with the corresponding value, then the operation is similar to the above.

                 $ ("#CustomerType"). Select2 ("Val", info. CustomerType);                 $ ("#Grade"). Select2 ("Val", info. Grade);                 $ ("#CreditStatus"). Select2 ("Val", info. Creditstatus);                 $ ("#Importance"). Select2 ("Val", info. importance);                 $ ("#IsPublic"). Select2 ("Val", info. IsPublic);

If cascade display is required, then the practice of adding a onchange function can be done, such as the assignment of the subordinate code as follows.

                 $ ("#Province"). Select2 ("Val", info. province). Trigger ('change ');//Linkage                 $ ("#City"). Select2 ("Val", info. City). Trigger (' change ');//Linkage                 $ ("#District"). Select2 ("Val", info. DISTRICT);
                $ ("#Company_ID1"). Select2 ("Val", info.company_id). Trigger ('change ');                $ ("#Dept_ID1"). Select2 ("Val", info. dept_id). Trigger (' change ');                $ ("#PID1"). Select2 ("Val", info. PID);

Finally, two integrated interface effects are provided for reference.

If you are interested, you can continue to refer to the series articles:

Metronic-based Bootstrap development Framework Experience Summary (1)-Framework Overview and Menu module processing

Experience summary of Bootstrap development framework based on Metronic (2)--The use of list paging and plug-in Jstree

Metronic-based Bootstrap development Framework Experience Summary (3)--use of drop-down list Select2 plugin

Experience summary of Bootstrap development framework based on metronic (4) extraction and utilization of--bootstrap icon

Experience summary of Bootstrap development framework based on Metronic (5)--bootstrap File upload plugin use

Experience summary of Bootstrap development framework based on metronic (6)--Processing and optimization of dialog box and prompt box

Transferred from: http://www.cnblogs.com/wuhuacong/p/4761637.html

Metronic_ drop-down list Select2 plug-in usage

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.