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

162
Vistas
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 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