Drop-down list multiple selection: bootstrap-select.js control, support drop-down multiple selection search, N styles

Reference URL: https://www.cnblogs.com/landeanfen/p/7457283.html#_label1

Read the table of contents

1. Component open source address and API description
2. Component effect example
3. Use example
      1. Basic example
      2. Other effect examples
      3. Component value assignment
      4. Other component usage
      5. Component packaging
4. Source code download
5. Summary

text

Foreword: I have shared two bootstrap drop-down box components before: JS component series-two kinds of bootstrap multiselect components competition and JS component series-Bootstrap Select2 component use summary, received a lot of attention and questions from garden friends, and finally summarized this The drop-down box components in the two articles have some large and small problems, such as the two bootstrap mutiselect components, the interface rendering effect is slightly worse; for example, some compatibility issues of select2, the value assignment of multiple selections, etc. are bothering bloggers. As well as many garden friends, the drop-down box in the project was replaced with the component introduced today, so I will introduce it to you today and let everyone have one more choice! Thank you for your continued attention!

Say something off topic. This article was originally prepared to write, but recently the project is going to take the front-end development route, but the blogger is busy. For a while, Node.js, npm, webpack, react, react-router, ant.design and other technologies are all You have to learn. The brain is really a good thing. It can accommodate so much new knowledge at once. Although it is not suitable for all kinds of things, it will gradually get used to it over time. Fortunately, bloggers often pay attention to this area of ​​technology, so they have not learned it. So strenuous. Regarding vue and react, many group friends have discussed their advantages and disadvantages. In fact, bloggers feel that they can’t say which component is better. The key depends on which ecology the project adapts to. A large part of the reason why we choose react is because we have fancy ant.design. The effect and rich component library. Okay, I'm off topic, and I'll talk more about it when bloggers share the front-end environment.

1. Component open source address and API description
bootstrap-select open source address: https://github.com/silviomoreto/bootstrap-select
bootstrap-select usage example: http://silviomoreto.github.io/bootstrap-select/examples/
bootstrap -Select document description: http://silviomoreto.github.io/bootstrap-select/options/

2. Examples of component effects at
first glance,
Insert picture description here
multiple selection effects
Insert picture description here

Configurable search function
Insert picture description here

Group selection
Insert picture description here

Set up to 2 selected items
Insert picture description here

Customize the title, for example, we define it as "Please select a province". In
Insert picture description here
some cases, if the number of multiple selections is large, we can display "Shortcut Mode". For example, when two or more are selected
Insert picture description here

Customized style
Insert picture description here
Display icons and text
Insert picture description here
Display colored labels
Insert picture description hereInsert picture description here
Expand to display the maximum number of configurable items, it is better to display up to 3 items
Insert picture description here
Select all and invert
Insert picture description here

The above are some commonly used functions, and more effects can be viewed in official examples!

Three, use example

1. Basic example
Since it is bootstrap-select, the component must depend on bootstrap, and bootstrap depends on jquery, so the following files must be referenced to use the component.

<link href="Content/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
<link href="Content/bootstrap-select/css/bootstrap-select.min.css" rel="stylesheet" />
<script src="Content/jquery-1.9.1.min.js"></script>
<script src="Content/bootstrap/js/bootstrap.min.js"></script>
<script src="Content/bootstrap-select/js/bootstrap-select.min.js"></script>
<script src="Content/bootstrap-select/js/i18n/defaults-zh_CN.min.js"></script>

The last file, defaults-zh_CN.min.js, is not necessary, and only needs to be referenced when it is cultured in the component.
It is even simpler to use, without any existing js, you can initialize it directly by using the class.

<select class="selectpicker">
    <option value="1">广东省</option>
    <option value="2">广西省</option>
    <option value="3">福建省</option>
    <option value="4">湖南省</option>
    <option value="5">山东省</option>                            
</select>

Just add selectpicker style to a select tag.

No need to say more than one choice

<select class="selectpicker" multiple>
    <option value="1">广东省</option>
    <option value="2">广西省</option>
    <option value="3">福建省</option>
    <option value="4">湖南省</option>
    <option value="5">山东省</option>                            
</select>

2. Examples of other effects

The above is the easiest way to use. Below, some commonly used effects will be given as code examples. For experts, please skip this section.
Add search function to components

<select class="selectpicker" multiple data-live-search="true">
    <option value="1">广东省</option>
    <option value="2">广西省</option>
    <option value="3">福建省</option>
    <option value="4">湖南省</option>
    <option value="5">山东省</option>                            
</select>

Option grouping

<select class="form-control selectpicker" data-live-search="true" multiple>
        <optgroup label="广东省">
                <option value="1">广州市</option>
                <option value="2">深圳市</option>
                <option value="3">珠海市</option>
         </optgroup>   
          <optgroup label="广西">
                  <option value="1">南宁市</option>
                  <option value="2">柳州</option>
                  <option value="3">桂林市</option>
           </optgroup>  
           <optgroup label="山东">
                   <option value="1">烟台</option>
                   <option value="2">青岛</option>
                   <option value="3">济南</option>
             </optgroup>                          
</select>

Set up to 2 selected items

<select class="selectpicker" multiple data-live-search="true" data-max-options="2">
    <option value="1">广东省</option>
    <option value="2">广西省</option>
    <option value="3">福建省</option>
    <option value="4">湖南省</option>
    <option value="5">山东省</option>                            
</select>

Abbreviated mode, for example, when the selected value is greater than 3, only the number of selected items is displayed. Note that this attribute is only valid for multiple selections

<select class="selectpicker" multiple data-live-search="true" data-selected-text-format="count > 3">
    <option value="1">广东省</option>
    <option value="2">广西省</option>
    <option value="3">福建省</option>
    <option value="4">湖南省</option>
    <option value="5">山东省</option>                            
</select>

Show colored labels

 <select class="form-control selectpicker" title="请选择省份" multiple>
                        <option data-content="<span class='label label-success'>广东省</span>">广东省</option>    
                        <option data-content="<span class='label label-info'>广西省</span>">广西省</option>  
                        <option data-content="<span class='label label-warning'>福建省</span>">福建省</option>  
                        <option data-content="<span class='label label-danger'>山东省</span>">山东省</option>                        
</select>

Default style selection

<select class="selectpicker" data-style="btn-primary">
  ...
</select>

<select class="selectpicker" data-style="btn-info">
  ...
</select>

<select class="selectpicker" data-style="btn-success">
  ...
</select>

<select class="selectpicker" data-style="btn-warning">
  ...
</select>

<select class="selectpicker" data-style="btn-danger">
  ...
</select>

Insert picture description here
3. Component value assignment

The above are some things for the initialization of the component. In general, we need to get and assign values ​​to the component. How should we operate it.

3.1, component value

Regarding the component value keeping the original jquery method, such as var value = $('#sel').val(); Is this very simple? It should be noted that if it is multiple selection, the value variable obtained here is an array Variable, like ['1','2','3'].

3.2, component assignment

The component assignment needs to be changed slightly. If you directly $('#sel').val('1'); then the assignment will be invalid. The correct assignment method is:

$(’.selectpicker’).selectpicker(‘val’, ‘1’);

In some usage scenarios of cascading selection, it is often necessary to trigger the change event of the component by the way when assigning a value. We can do this.

$(’.selectpicker’).selectpicker(‘val’, ‘1’).trigger(“change”);

If it is a multiple choice assignment, the same is true

$(’.selectpicker’).selectpicker(‘val’, [‘1’,‘2’,‘3’]).trigger(“change”);

4. Other usage of components

Select all: $('.selectpicker').selectpicker('selectAll');
Invert selection: $('.selectpicker').selectpicker('deselectAll');
Adapt to mobile phone mode: $('.selectpicker').selectpicker(' mobile');

Component disabled:

$(’.disable-example’).prop(‘disabled’, true);
$(’.disable-example’).selectpicker(‘refresh’);

Component activation:

$(’.disable-example’).prop(‘disabled’, false);
$(’.disable-example’).selectpicker(‘refresh’);

Component destruction:

$(’.selectpicker’).selectpicker(‘destroy’);

5. Component packaging

There are so many introductions about the initialization of components above, all of which are initialized through class='selectpicker'. In many cases, the options of our select are dynamically obtained and then initialized, so the blogger carefully looks for the api, See if there is remote access to data in it. Unfortunately, the component does not support this method of remote access to data. It doesn't matter, how difficult is it to encapsulate an ajax request by ourselves and then dynamically construct the option? Here I have to mention the original article about encapsulating js components. We just need to encapsulate one according to the idea of ​​that article. A reference is given below.

(function ($) {
    //1.定义jquery的扩展方法bootstrapSelect
   $.fn.bootstrapSelect = function (options, param) {
       if (typeof options == 'string') {
           return $.fn.bootstrapSelect.methods[options](this, param);
       }
       //2.将调用时候传过来的参数和default参数合并
       options = $.extend({}, $.fn.bootstrapSelect.defaults, options || {});
       //3.添加默认值
       var target = $(this);
       if (!target.hasClass("selectpicker")) target.addClass("selectpicker");
       target.attr('valuefield', options.valueField);
       target.attr('textfield', options.textField);
       target.empty();
       var option = $('<option></option>');
       option.attr('value', '');
       option.text(options.placeholder);
       target.append(option);
       //4.判断用户传过来的参数列表里面是否包含数据data数据集,如果包含,不用发ajax从后台取,否则否送ajax从后台取数据
       if (options.data) {
           init(target, options.data);
       }
       else {
           //var param = {};
           options.onBeforeLoad.call(target, options.param);
           if (!options.url) return;
           $.getJSON(options.url, options.param, function (data) {
               init(target, data);
           });
       }
       function init(target, data) {
           $.each(data, function (i, item) {
               var option = $('<option></option>');
               option.attr('value', item[options.valueField]);
               option.text(item[options.textField]);
               target.append(option);
           });
           options.onLoadSuccess.call(target);
       }
       target.unbind("change");
       target.on("change", function (e) {
           if (options.onChange)
               return options.onChange(target.val());
       });
   }

   //5.如果传过来的是字符串,代表调用方法。
   $.fn.bootstrapSelect.methods = {
       getValue: function (jq) {
           return jq.val();
       },
       setValue: function (jq, param) {
           jq.val(param);
       },
       load: function (jq, url) {
           $.getJSON(url, function (data) {
               jq.empty();
               var option = $('<option></option>');
               option.attr('value', '');
               option.text('请选择');
               jq.append(option);
               $.each(data, function (i, item) {
                   var option = $('<option></option>');
                   option.attr('value', item[jq.attr('valuefield')]);
                   option.text(item[jq.attr('textfield')]);
                   jq.append(option);
               });
           });
       }
   };

   //6.默认参数列表
   $.fn.bootstrapSelect.defaults = {
       url: null,
       param: null,
       data: null,
       valueField: 'value',
       textField: 'text',
       placeholder: '请选择',
       
   };

   //初始化
   $(".selectpicker").each(function () {
    var target = $(this);
    target.attr("title", $.fn.select.defaults.placeholder);
    target.selectpicker();
});
})(jQuery);

After this encapsulation, we can directly use the following code to initialize the component.

$('#sel').bootstrapSelect({
    url:'/a/b',
    data: {},
    valueField: 'value',
    textField: 'text',
});

Four, summary

At this point, this article is over. Looking at all of the select components of bootstrap, this one is slightly easier to use. Both compatibility and implementation effects are not bad. If you are interested, you can try it.

Six, the problems encountered

1. The problem encountered when using this control in the project 1: Use it in the tab tab, initialize the first tab to have a drop-down box, and there is no
reason for the other tabs : because there is only one element id, and each tab is under There is a drop-down box element, and the id is unique, so when initializing, the following elements
can not be selected. Solution: Give a different id or class, initialize: $('#selectContacts0').selectpicker();
Insert picture description here
2 . The second problem encountered in using this space in the project: When clicking each tab, the selected state of the previous tab is always retained.
Reason: When each tab is clicked, the check box under the current tab needs to be cleared and Initialization
Solution: When you click on each tab, execute:
$(".selectpicker").selectpicker('val','');//Return to the initial state
$(".selectpicker).selectpicker('refresh') ;
3. Three problems encountered in using this space in the project: one-key selection and one-key reverse selection (the built-in function display is in English, you can manually change Chinese by yourself);
solution: add data-actions on the multi -select box The -box="true" attribute is the inverse selection function. Use jquery to select the inverse selection element and manually assign the value to Chinese
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_43996999/article/details/97244555