简体   繁体   English

向 select 添加选项并使用 select2

[英]Adding options to a select and using select2

I am trying to add options to a select drop down list.我正在尝试向select下拉列表添加选项。 I am doing this dynamically with js .我正在用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.当我使用一个select列表执行此操作时,它可以工作,但我需要动态添加更多select列表,因为用户想要添加更多集合。

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 .我注意到当我console.log(e)我得到一个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.我访问它的options并添加到它。 It works great.它很好用。

When I add the select menu dynamically I do this:当我动态添加 select 菜单时,我会这样做:

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 .当我在这里使用console.log(input)时,我得到一个Object I'm sure that this is my problem I just don't know how to push or add to the Object .我确定这是我的问题,我只是不知道如何推送或添加到Object Is there a different way I need to be adding to an object?我需要添加到 object 的其他方式吗? What am I doing wrong here?我在这里做错了什么?

I found the official select2 documentation very simple when it comes to managing options.在管理选项方面,我发现官方 select2 文档非常简单。 For example, you can use the code snippet below to append and select option.例如,您可以使用下面的代码片段来选择 append 和 select 选项。 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 https://select2.org/programmatic-control/add-select-clear-items

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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