Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

115
Visualizações
Dynamically setting options for a select elements skips first element

I've dynamically built an options array divided in two options group. These options groups are stored in a javascript array named ogs. The code for the same is as below:

var ogs = [];
for (optGroup in optionsList) {
    var og = document.createElement('optgroup');
    og.label = optGroup;
    var ops = optionsList[optGroup];
    for (op in ops) {
        var o = document.createElement('option');
        o.value = op;
        o.text = ops[op];
        og.appendChild(o);
    }
    ogs.push(og);
}

Now, I'm trying to add these options to 2 select elements, as below:

var from_el = document.getElementById('from_selector'), to_el = document.getElementById('to_selector');
for (i = 0; i < ogs.length; ++i) {
    var og = ogs[i];
    from_el.add(og);
    to_el.add(og);
}

However, at the end of the script, only to_selector has the options populated, whereas from_selector remains empty. The reason I'm populating the options like this is because both these select elements use select2, and any other method (such as innerHTML) is taking significantly longer. I've also tried putting these selectors in array and iterating over them, always the last select gets populated, whereas first select remains empty.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Figured out the issue. The problem was in the following lines:

from_el.add(og);
to_el.add(og);

When og was getting added to to_el, it was getting detached from from_el. The solution was to replace this with.

from_el.add(og);
to_el.add(og.cloneNode(true));
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda