[英]add remove dynamic select box not add data to dynamic input
我有此代码用于添加动态 select 框并为每个框加载 select2 搜索,如下所示:
<script type="text/javascript">
var attribute_row = <?= $attribute_row; ?>;
function addAttribute() {
html = '<tr id="attribute-row' + attribute_row + '">';
html += ' <td class="text-left"><input type="text" name="product_attribute[' + attribute_row + '][name]" class="attribute-name' + attribute_row + '" value=""><select id="' + attribute_row + '" name="product_attribute[' + attribute_row + '][attribute_id]" class="form-control attributeSelect">';
html += ' </select></td>';
html += ' <td><div class="icheck-primary"><input type="checkbox" id="checkboxAttribute' + attribute_row + '" name="product_attribute[' + attribute_row + '][visible_on_product]" value="1"><label for="checkboxAttribute' + attribute_row + '"></label></div></td>';
html += ' <td><input type="text" name="product_attribute[' + attribute_row + '][text]" value="" placeholder="<?= lang('Product.price'); ?>" class="form-control" /></td>';
html += ' ';
html += ' <td><button type="button" onclick="$(\'#attribute-row' + attribute_row + '\').remove();" data-toggle="tooltip" title="<?= lang('Product.removeAttribute'); ?>" class="btn btn-danger"><i class="fa fa-minus-circle"></i></button></td>';
html += '</tr>';
$('#attribute tbody').append(html);
$(".attributeSelect").select2({
minimumInputLength: 3,
theme: 'bootstrap4',
width: 'auto',
ajax: {
url: "url",
type: "post",
dataType: 'json',
delay: 250,
data: function (params) {
return {
searchTerm: params.term,
csrf_token: csfr_token // search term
};
},
processResults: function (response) {
return {
results: response
};
},
cache: true
}
}).on("select2:select", function () {
data = $(".attributeSelect").select2('data')[0];
id = $('.attributeSelect').attr('id');
$(".attribute-name" + id).val(data.text);
});
attribute_row++;
}
</script>
在搜索和选择后的操作( on select
)结果我需要将 select2 data.text
添加到此输入框中:
<input type="text" name="product_attribute[' + attribute_row + '][name]" class="attribute-name' + attribute_row + '" value="">
我的代码适用于第一个 select 框并将值添加到第一个输入框但对于第二个和更多也将数据添加到第一个输入。
我该如何解决这个问题?
为所有具有该 class 的项目执行此操作时,您总是会获得第一个 ID:
id = $('.attributeSelect').attr('id');
这就是为什么它总是将结果设置为第一个元素。 您应该获取接收事件的元素的当前 id。 您可能会从事件 object 中收到它:
$('#mySelect2').on('select2:select', function (e) {
console.log(e);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.