Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

114
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!