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

161
Visualizações
Adding options to a select and using select2

I am trying to add options to a select drop down list. I am doing this dynamically with js.

When I do this with one select list it works but I need to dynamically add more select list as the user wants to add more sets.

My one list works just fine like this:

<body>
<select class="js-example-basic-single" name="state"></select>
</body>

<script>
$(document).ready(function() { 
    $('.js-example-basic-single').select2();
});

load_workout_lst({{workout_list | tojson}});

let lst = {{workout_list | tojson}};
let e = document.getElementsByName('state');
console.log(e);
for(var i = 0, l = lst.length; i < l; i++){
    var option2 = lst[i];
    e[0].options.add(new Option(option2));
}
</script>

I notice when I console.log(e) I get a NodeList. Since I know there is only one item in that list I choose the first one. I access its options and add to it. It works great.

When I add the select menu dynamically I do this:

let exercise = $("#exercise");
var input;
var input = $("<select>").attr("type", "text").attr("name", exerciseName).attr("tabindex", tabIndexNum);  
var br = $("<br>");
exercise.append(br);
exercise.append(input);
input.select2();
console.log(input);
for(var i = 0, l = workout_lst.length; i < l; i++){
    console.log(workout_lst[i]);
    var item = workout_lst[i];
    input.options.add(new Option(item));
}
tabIndexNum++;

var workout_lst = [];

function load_workout_lst(lst){
    for (let i = 0; i < lst.length; i++){
        workout_lst.push(lst[i]);
    }
}

Error:

Uncaught TypeError: input.options is undefined

When I console.log(input) here I get an Object. I'm sure that this is my problem I just don't know how to push or add to the Object. Is there a different way I need to be adding to an object? What am I doing wrong here?

about 4 years ago · Juan Pablo Isaza
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