[英]dynamic options in select2 after click in some button
I'm using Select2 in my website and I need to reload (change) the options in the select with new ones after some user interaction.我在我的网站中使用Select2 ,我需要在一些用户交互后使用新选项重新加载(更改)选择中的选项。
I have this:我有这个:
When I chose one day, I need to reload hours.当我选择某一天时,我需要重新加载时间。 Because each day has different hours available, like this:因为每天都有不同的可用时间,如下所示:
This is my javascript
object with all the info I need (No AJAX needed):这是我的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"]
}
]
}
]
I've been trying with $('#selectId').select2({ data: data })
but it only adds data
to the current data
available and it only works once.我一直在尝试$('#selectId').select2({ data: data })
但它只将data
添加到当前可用的data
,并且只能工作一次。 Second time is not adding anymore.第二次不再添加了。
I want to delete options and set new ones.我想删除选项并设置新选项。 I'm using this variable from select2 doc's:我正在使用 select2 文档中的这个变量:
var data = [
{ id: 0, text: 'enhancement' },
{ id: 1, text: 'bug' },
{ id: 2, text: 'duplicate' },
{ id: 3, text: 'invalid' },
{ id: 4, text: 'wontfix' }
];
Summarize : I want to change the data of the HOURS select when the DAYS select changes.总结:当DAYS选择改变时,我想改变HOURS选择的数据。
Any help?有什么帮助吗? Thanks!谢谢!
I found this question from a few years ago, and one answer suggests calling .html('')
on the element before adding the new data options...几年前我发现了这个问题,一个答案建议在添加新数据选项之前在元素上调用.html('')
...
Try this:尝试这个:
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.