I have problem with iteration in jquery that i dont understand. I grab all select2 elements having given name and try to append new option:
var newOption = new Option(model.nazwa, model.id, false, false);
$('select[name="grupa_cechy_id"]').each(function () {
$(this).append(newOption).trigger('change');
//check the loop works
let idx = $(this).attr('id');
console.log(idx);
});
The loop works but only last select2 element from the loop gets new option. How to fix that?
DOM elements can have only a single parent. What you're actually doing, is attempting to append the element to multiple parents, which effectively just moves it around in the DOM. Thus, it will continuously be moved until the last element in the loop, when it is no longer appended to any other elements.
You should refactor your code, and create a new option each time the loop is iterated, as follows:
$('select[name="grupa_cechy_id"]').each(function () {
const newOption = new Option(model.nazwa, model.id, false, false);
$(this).append(newOption).trigger('change');
});