[英]How to control the select box when I add new one?
I'm working with bootstrap-select and I have the group of inputs that user add it as he wants, but just the first select box runs ok with the plugin but others inputs don't我正在使用bootstrap-select并且我有一组输入,用户可以根据需要添加它,但是只有第一个选择框可以与插件一起运行,但其他输入却没有
HTML code: HTML代码:
<div id="products-color">
<div class="form-group">
<select class="selectpicker" data-live-search="true" name="color_id" style="width:100%">
@foreach($colors as $color)
<option value="{{ $color->id }}">{{ $color->name }}</option>
@endforeach
</select>
</div>
</div>
<button type="button" class="btn btn-tiffany" onclick="addColorOption()">Add New </button>
js code: js代码:
function addColorOption() {
var color = `
<div class="form-group">
<select class="selectpicker" data-live-search="true" name="color_id" style="width:100%">
@foreach($colors as $color)
<option value="{{ $color->id }}">{{ $color->name }}</option>
@endforeach
</select>
</div>
`;
$('#products-color').append(color);
}
bootstrap select plugin:引导选择插件:
$('.selectpicker').selectpicker();
That's means just the first select box runs with the plugin but when I add a new select box by add new
button the plugin does not work这意味着只有第一个选择框与插件一起运行,但是当我通过add new
按钮添加新的选择框时,插件不起作用
You need to put $('.selectpicker').selectpicker();
你需要把$('.selectpicker').selectpicker();
as last line of addColorOptions
method to initialize the newly added select.作为addColorOptions
方法的最后一行来初始化新添加的选择。
As we are adding a bootstrap-select
dynamically, we need to initialize them after creating them.当我们动态添加bootstrap-select
,我们需要在创建它们后初始化它们。 You can find the documentation bootstrap-select here您可以在此处找到文档bootstrap-select
when everything is working fine and just dynamically added select inputs not rendering as expected当一切正常并且只是动态添加的选择输入未按预期呈现时
function addColorOption() {
var color = `
<div class="form-group">
<select class="selectpicker" data-live-search="true" name="color_id" style="width:100%">
@foreach($colors as $color)
<option value="{{ $color->id }}">{{ $color->name }}</option>
@endforeach
</select>
</div>
`;
$('#products-color').append(color);
$('.selectpicker').selectpicker(); //just adding it here will do
}
``
The select
elements generated with addColorOption()
should each have a unique name
value, not the same as your original element.使用addColorOption()
生成的select
元素每个都应该有一个唯一的name
值,而不是与原始元素相同。 You could generate a number based on the number of existing selects each time and append it to the name of the new element.您可以根据每次现有选择的数量生成一个数字,并将其附加到新元素的名称中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.