0

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?

And1
  • 11
  • 2
  • 2
    Move the creating of the new option *inside* the iteration. DOM elements can only have one parent, trying to add the to multiple ones just moves them – VLAZ Jun 17 '22 at 10:50
  • 1
    Create the option inside of the loop instead. – BenM Jun 17 '22 at 10:50

1 Answers1

1

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');
});
BenM
  • 52,573
  • 26
  • 113
  • 168