简体   繁体   中英

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?

I found the official select2 documentation very simple when it comes to managing options. For example, you can use the code snippet below to append and select option. For more details, i have left a reference.

var data = {
    id: 1,
    text: 'Barn owl'
};

var newOption = new Option(data.text, data.id, true, true);
$('#mySelect2').append(newOption).trigger('change');

Reference:
https://select2.org/programmatic-control/add-select-clear-items

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM