Can I search something in <select> and select all

501 Views Asked by At
<select id="agent" name="agentid" class="selectpicker" data-live-search="true" multiple>
  <option value="">none</option>
  ...<!--other options-->...
</select>

how can I offer a btn when I finish search and select all the option?

1

There are 1 best solutions below

0
On

I solved it by myself!

I add a method called selectQuery to bootstrap-select.js

/*!
 * bootstrap-select v1.4.1
 * http://silviomoreto.github.io/bootstrap-select/
 *
 * Copyright 2013 bootstrap-select
 * Licensed under the MIT license
 */
var Selectpicker = function(element, options, e) {
    if (e) {
        e.stopPropagation();
        e.preventDefault();
    }
    this.$element = $(element);
    this.$newElement = null;
    this.$button = null;
    this.$menu = null;

    //Merge defaults, options and data-attributes to make our options
    this.options = $.extend({}, $.fn.selectpicker.defaults, this.$element.data(), typeof options == 'object' && options);

    //If we have no title yet, check the attribute 'title' (this is missed by jq as its not a data-attribute
    if (this.options.title === null) {
        this.options.title = this.$element.attr('title');
    }

    //Expose public methods
    this.val = Selectpicker.prototype.val;
    this.render = Selectpicker.prototype.render;
    this.refresh = Selectpicker.prototype.refresh;
    this.setStyle = Selectpicker.prototype.setStyle;
    //this is what I add
    this.selectQuery = Selectpicker.prototype.selectQuery;
    this.selectAll = Selectpicker.prototype.selectAll;
    this.deselectAll = Selectpicker.prototype.deselectAll;
    this.init();
};


selectQuery: function(){
        var lis = this.$newElement.find('li');
        var options = this.$element.find('option');
        for(var i = 0 ;i<lis.length;i++){
            if(lis.eq(i).css('display') != 'none'){
                options.eq(i).prop('selected', true).attr('selected', 'selected');
            }
        }
        this.render();
    },

To trigger selectQuery, just add a btn and add click event

<button type="button" class="btn btn-success btn-sm" id="selectbtn">全选</button>
<script type="text/javascript">
$(function(){
    $('#selectId').selectpicker();
    $("#selectbtn").click(function(){
        $('#selectId').selectpicker('selectQuery');
    });
}
</script>