我对 JQuery/Bootstrap-Select 插件相当陌生,并且在单击“添加”按钮时,我一直在讨论添加多个选择框:
我正在使用 Bootstrap v3.3.5、jQuery v2.1.4 和 Bootstrap-select v1.11.2。
以下是我的 HTML 代码:
<h2>Vehicle Details</h2>
<div class="row">
<div class="vehicle_wrapper">
<div class="col-xs-3 col-sm-3 col-md-3">
<select name="vehicle_make[]" data-live-search="true" class="form-control" placeholder="Vehicle Make" required>
<option value="">Vehicle Make</option>
{foreach item=makes from=$makes_array key=m}
<option value="{$makes->make_id}">{$makes->make_name}</option>
{/foreach}
</select>
</div>
<div class="col-xs-3 col-sm-3 col-md-3">
<select name="vehicle_model[]" data-live-search="true" class="form-control" placeholder="Vehicle Model" disabled>
<option value="">Vehicle Model</option>
</select>
</div>
<div class="col-xs-3 col-sm-3 col-md-3">
<div class="form-group">
<input type="text" class="form-control" name="vehicle_vrm[]" value="" placeholder="Vehicle VRM" />
</div>
</div>
<div class="col-xs-3 col-sm-3 col-md-3">
<div class="form-group">
<input type="text" class="form-control" name="vehicle_vin[]" value="" placeholder="Vehicle VIN" />
</div>
</div>
</div>
<div id="moreVehicles"></div>
<div class="col-xs-2 col-sm-2 col-md-2 pull-right"><input class="btn btn-success button exrta" type="button" id="addVehicle" value="Add +" > <input class="btn btn-danger button exrta" type="button" id="cancelVehicle" value="Remove -" ></div>
</div>
我的 JS/JQuery 代码如下:
$(document).ready(function() {
$('select').selectpicker();
var vehicles = $("select[name='vehicle_make[]']").length;
var allowed_vehicles = vehicles;
$("#addVehicle").click(function (event) {
if( $('.vehicle_wrapper').length > 0 ){
var html = $('.vehicle_wrapper').html();
$('#moreVehicles').append('<div class="vehicle'+vehicles+'">' + html + '</div>');
if( $("#moreVehicles .vehicle"+vehicles+" select").length > 0 ){
$('select').selectpicker('refresh');
}
}
vehicles++;
event.preventDefault();
});
$("#cancelVehicle").click(function(event){
if(vehicles > allowed_vehicles){
vehicles--;
event.preventDefault();
$('.vehicle'+vehicles+'').remove();
}
});
});
下面是我点击添加按钮时的屏幕截图,它会检查元素是否存在然后刷新选择框。出于某种奇怪的原因,它在其下方添加了另一个选择框副本。但是,如果我取出代码的刷新行,那么您将无法选择选择框中的选项。
任何帮助将非常感激。感谢您抽出宝贵时间调查此事。