如何使用bootstrap-select动态设置多个值

问题描述 投票:1回答:1

我需要使用bootstrap-select插件动态设置多个值。我在下面提供我的代码。

<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="col-md-2" style=" width: 13.3%; max-width: 100%;">
<label for="" class="control-label" style="text-align:left;">Menu:</label>
</div>
    <div class="col-md-10 well" style="max-height:220px;overflow-y: auto;max-width: 100%;width: 85%;">
<div class="row" id="examMenuGroup"></div>
            </div>
        </div>
    </div>
</div>

var options = "<div class='col-md-12'><label class='checkbox-inline'><input type='checkbox' id='allmenu' onclick='checkAll(this.id)'><strong>Select All</strong></label></div></br>";
    var menuArr=[{'menu_name':'Document','id':1},{'menu_name':'Profile','id':2},{'menu_name':'Fee','id':3},{'menu_name':'Communication','id':4}];
    $.each(menuArr,function(i,data)
    { 
        options = options + "<div class='col-md-2'><label class='checkbox-inline'><input type='checkbox' name='chkmenu[]' data-label='"+data.menu_name+"' id='chkMenu"+data.id+"' value='"+data.menu_name+"'>"+data.menu_name+"</label></div>";
    });
    $('#examMenuGroup').html("");   
    $('#examMenuGroup').append('<%=Encoder.encodeForJS('+options+')%>');
    $('#examMenuGroup').html(options)
    .selectpicker('refresh');

在这里,我在check box插件中设置了bootstrap-select值。但在这里我的要求是我需要设置值(i.e-Document,Profile)使用一些点击事件意味着当用户点击任何按钮这些(i.e-Document,Profile)值将在复选框中动态选择。

javascript jquery bootstrap-select
1个回答
1
投票

要设置多个值,需要将值作为数组传递。要清除值,请将""null作为值传递。

$(document).ready(function(){
    $(".add").click(function(){
        var options =  $(this).data("options").split(",");
        $(".selectpicker").val(options).selectpicker("refresh"); //The following one can also be used. It handles refresh internally.
        //$(".selectpicker").selectpicker("val",options);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/css/bootstrap-select.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/js/bootstrap-select.min.js"></script>

<select class="selectpicker" multiple>
  <option>Idli</option>
  <option>Dosai</option>
  <option>Panayaram</option>
  <option>Poori</option>
</select>
<br><br>
<button class="add btn btn-primary" data-options="Idli,Dosai">Add Idli, Dosai</button>
<button class="add btn btn-success" data-options="Poori,Dosai">Add Poori, Dosai</button>
<button class="add btn btn-warning" data-options="Panayaram">Add Panayaram</button>
<button class="add btn btn-info" data-options="Poori">Add Poori</button>
<button class="add btn btn-danger" data-options="">Clear</button>
© www.soinside.com 2019 - 2024. All rights reserved.