我可以在<select>中搜索并选择所有</select>

时间:2013-12-18 08:30:51

标签: bootstrap-select

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

当我完成搜索并选择所有选项时,如何提供btn?

1 个答案:

答案 0 :(得分:0)

我自己解决了!

我将一个名为selectQuery的方法添加到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();
    },

要触发selectQuery,只需添加一个btn并添加click事件

<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>