I am fairly new to JQuery/Bootstrap-Select plugin and I have been going around in circles regarding adding multiple select boxes when clicking the Add button:
I am using Bootstrap v3.3.5, jQuery v2.1.4 and Bootstrap-select v1.11.2.
The following is my HTML code:
<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>
My JS/JQuery code is the following:
$(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();
}
});
});
Below is my screenshot on how it looks like when the Add button is clicked and it checks if the element exists then refresh the select box. For some strange reason it adds another copy of the select box underneath it. However, if I take out the refresh line of code then you can not select the options within the select box.
When the refresh line is commented out, the output below is displayed but I can not select the option.
Any help would be much appreciated. Thank you for taking out your time in looking into this matter.