Summary of experience on Bootstrap Metronic development framework "three" dropdown list Select2 use _javascript tips

Source: Internet
Author: User
Tags list of attributes

In the last chapter, based on the experience of Bootstrap Metronic development framework "Two" list paging processing and plug-in jstree use, introduced the data paging processing, the use of the bootstrap Paginator Plug-ins, in addition to the tree list, the use of the Jstree plug-ins, This article continues to describe the control Select2 that is commonly used in editing pages, which can enrich the traditional select Drop-down list controls to provide more functionality and a better user experience.

1, Select2 Control introduction

This plug-in is based on select extension, can provide a richer functionality and user experience, its GitHub official website address: https://select2.github.io/, the use of specific cases, you can refer to the address: https:// Select2.github.io/examples.html.

We used a lot of Select2 controls inside the frame to handle the display of the content, including the Radio Drop-down list (including cascading selection box), check drop-down list, tree Drop-down list, and so on, the interface effect is shown below.

1 Edit the interface of the provinces, cities, the region of the Cascade interface effect , select the province, will load the corresponding provinces under the city, select the city, will continue to load the city under the administrative district, so as to achieve multi-level associated drop-down list effect.

2 Select Drop-down List of multiple items under the editing interface

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

3 Drop-down List of tree-type lists

Sometimes, some of our data may have hierarchical relationships, such as owning an organization, a list of the upper layers, and so on.

2, Select2 control of the actual use of code analysis

1 basic interface Code and operation

You can use the Select2 control, typically on a regular select control, and set it up (set its class to Select2).

<div class= "col-md-6" >
  <div class= "Form-group" >
    <label class= "Control-label col-md-4" > Important level </label>
    <div class= "col-md-8" >
      <select id= "importance" name= "importance" Form-control Select2 "placeholder=" important level ... "></select>
    </div>
  </div>
</div >
 <div class= "col-md-6" >
  <div class= "Form-group" >
    <label class= "Control-label Col-md-4 "> Accreditation degree </label>
    <div class=" col-md-8 ">
      <select id=" Recognition "name=" Recognition "class=" Form-control select2 "placeholder=" recognition degree ... "></select>
    </div>
  </ Div>
</div>

If it is a fixed list, then the option content is set, 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 initializes the code as 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 through Ajax and bind it.

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

Bind dictionary contents to the specified Select control
function bindselect (ctrlname, url) {
  var controls = $ (' # ' + ctrlname);
  Set the processing control.select2 for Select2
  ({
    allowclear:true,
    formatresult:formatresult,
    formatselection: Formatselection,
    escapemarkup:function (m) {return
      m;
    }
  });

  Bind Ajax content
  $.getjson (URL, function (data) {
    control.empty ();/clear dropdown box
    $.each (data, function (I, item) {
      control.append ("<option value=") + item. Value + "' >" + item. Text + "</option>");});}

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

Bind 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 initializing the code below. Where Binddictitem is directly binding the contents of the dictionary operation, Bindselect is based on the URL to obtain and bind data, and $ ("#Province"). On (' Change ', function (e) {}); is to deal with the changes in the selection of the linkage operation.

//initialization dictionary information (Drop-down list) function Initdictitem () {//Partial assignment Reference Binddictitem ("Ar
      EA "," market zoning ");
      Binddictitem ("Industry", "Customer industry");
      Binddictitem ("Grade", "Customer Level");
      Binddictitem ("CustomerType", "Customer Type");
      Binddictitem ("source", "Customer Source");
      Binddictitem ("Creditstatus", "Credit Grade");
      Binddictitem ("Stage", "Customer Stage");
      Binddictitem ("Status", "Customer status");   
      Binddictitem ("Importance", "important level");
      Binding provinces, cities, administrative districts (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);
    }); }

And where the MVC controller returns the data, we are returning a list of JSON data to the front page, and their data format is 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 binds the Select2 control, it uses the properties of the JSON object.

Bind Ajax content
  $.getjson (URL, function (data) {
    control.empty ();/clear dropdown box
    $.each (data, function (I, item) {
      control.append ("<option value=") + item. Value + "' >" + item. Text + "</option>");
    });
  

The implementation code for the controller is as follows:

 <summary>
    ///Gets the corresponding dictionary data according to the dictionary type to facilitate the binding of 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 The binding operation of the tree-type list

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

 Bindings add the interface of the company, department, directly under the manager
      bindselect ("company_id", "/user/getmycompanydictjson?userid=" + @Session ["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 an 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 ":" Development of a group "," value ":" A "}, {" Text ":" Development Two groups "," Value ":" 15 "}, {"Text": "Test Group", "Value": ""}, {"text": "Marketing Department", "value": "Ten"}, {"Text": "Market One", "Value": "" "}, {" Text ":" City Field two "," Value ":" "}, {" text ":" Integrated department "," value ":" One "}, {" Text ":" Production department "," value ":" A "}, {" Text ":" Human Resources department "," value ":" 13 " } ]

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

But from this interface effect, this kind of processing does not have easyui inside, the display of the dropdown tree is good-looking, perhaps can use the better bootstrap plug-in to carry on the display of this tree content.

4) Assignment processing of SELECT2 control

The method described above is to introduce the initialization of the Select2 control, binding related data, then if you initialize the interface, when we bind the value of the editing interface, we need to assign a value to the control, so that it displays the items that really need to be displayed.

The method for emptying the control is shown below.

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

If you need to clear 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 that corresponds to the value, and 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 cascading is required, then it is possible to add a onchange function processing, such as assigning the subordinate code to the following procedure.

 $ ("#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 comes the two integral interface effect for reference.

The above is a small part of the introduction of bootstrap Metronic development framework based on the experience of "three" Drop-down list of the use of Select2 plug-ins related content, I hope to help you, if you want to learn more information please pay attention to cloud Habitat community website!

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.