Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

116
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda