gpt4 book ai didi

javascript - 单击某个按钮后 select2 中的动态选项

转载 作者:太空宇宙 更新时间:2023-11-04 16:31:23 24 4
gpt4 key购买 nike

我在网站中使用 Select2,在进行一些用户交互后,我需要使用新选项重新加载(更改)选择中的选项。

我有这个:

enter image description here

当我选择某一天时,我需要重新加载时间。因为每天都有不同的可用时间,如下所示:

enter image description here

这是我的 javascript 对象,其中包含我需要的所有信息(不需要 AJAX):

var ob = [
{
// Don't worry about activityId
activityId: '1234',
days: [
{
//Some date format
id: '20161001',
//Available hours for each day
hours: ["10:00", "11:00"]
},
{
id: '20161002',
hours: ["10:00", "12:00"]
}
]
},
{
activityId: '4567',
days: [
{
id: '20161003',
hours: ["10:30", "19:00"]
},
{
id: '20161002',
hours: ["10:00", "14:00"]
}
]
}
]

我一直在尝试使用 $('#selectId').select2({ data: data }) 但它只将 data 添加到当前 数据可用,并且只能运行一次。第二次就不再添加了。

我想删除选项并设置新选项。我正在使用 select2 文档中的这个变量:

var data = [
{ id: 0, text: 'enhancement' },
{ id: 1, text: 'bug' },
{ id: 2, text: 'duplicate' },
{ id: 3, text: 'invalid' },
{ id: 4, text: 'wontfix' }
];

总结:我想在 DAYS 选择更改时更改 HOURS 选择的数据

有什么帮助吗?谢谢!

最佳答案

我找到了this question几年前,一个答案建议在添加新数据选项之前在元素上调用 .html('')...

试试这个:

var ob = {
// Don't worry about activityId
activityId: '1234',
days: [
{
//Some date format
id: '20161001',
//Available hours for each day
hours: ["10:00", "11:00"]
},
{
id: '20161002',
hours: ["10:00", "12:00"]
}
]
};
var days = ob.days.map(function(day) {
return {id: day.id, text: day.id};
});

$("#e1").select2({data: days});
$("#e1").change(function(arguments) {
var value = $("#e1").val();
var day = ob.days.find(function(day) {
return day.id == value;
});
var selectList2 = $("#e2");
selectList2.html('');//this will clear the existing values
selectList2.select2({data: day.hours});
selectList2.show(); //in case it wasn't visible before
});
.select2 {
width:100%;
min-width: 100px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<select id="e1"></select>
<select id="e2" style="display: none"></select>

关于javascript - 单击某个按钮后 select2 中的动态选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39781240/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com