Reputation: 203
I have this code for add dynamic select box and load select2 search for each like this:
<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>
in Action after search and select(on select
) result i need to add select2 data.text
into this input box:
<input type="text" name="product_attribute[' + attribute_row + '][name]" class="attribute-name' + attribute_row + '" value="">
my code work for first select box and add value to first input box But for second and more also add data to first input.
how do can i fix this problem?
Upvotes: 0
Views: 47
Reputation: 816
You're always getting the first id when doing this for all the items with that class:
id = $('.attributeSelect').attr('id');
That's why it's setting always the result the first element. You should get the current id of the element receiving the event. You can probably receive that from the event object:
$('#mySelect2').on('select2:select', function (e) {
console.log(e);
});
Upvotes: 1