[英]SweetAlert2 add dynamic options to select input
我想向SweetAlert2输入类型 select 添加动态选项,如下所示:
swal({
title: 'Select Ukraine',
input: 'select',
inputOptions: {
'SRB': 'Serbia',
'UKR': 'Ukraine',
'HRV': 'Croatia'
},
inputPlaceholder: 'Select country',
showCancelButton: true,
inputValidator: function(value) {
return new Promise(function(resolve, reject) {
if (value === 'UKR') {
resolve();
} else {
reject('You need to select Ukraine :)');
}
});
}
}).then(function(result) {
swal({
type: 'success',
html: 'You selected: ' + result
});
})
我想添加自己的选项,而不是这 3 个国家/地区,这些选项保存在 object 中。我如何使用 javascript 来做到这一点?
您可以尝试像这样构建选项对象。
function linkThing() {
//this i assume would be loaded via ajax or something?
var myArrayOfThings = [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' }
];
var options = {};
$.map(myArrayOfThings,
function(o) {
options[o.id] = o.name;
});
swal({
title: 'My Title',
text: 'Please select an option',
input: 'select',
inputOptions: options,
showCancelButton: true,
animation: 'slide-from-top',
inputPlaceholder: 'Please select'
}).then(function (inputValue) {
if (inputValue) {
console.log(inputValue);
}
});
};
首先你需要创建一个 model 的例子:
{
"VALUE" : "TEXT",
"VALUE-2" : "TEXT-2",
"VALUE-3" : "TEXT-3"
}
对于获得选项后:
<option value="VALUE">TEXT</option>
然后,您需要将 model 创建为:
var model = [];
array.foreach(element => {
model[element.idObject] = element.textObject;
});
swal({
title: 'Title',
text: 'Description',
input: 'select',
inputOptions: model,
showCancelButton: true,
inputPlaceholder: 'Select a option'
}).then(function (inputValue) {
if (inputValue) {
console.log(inputValue);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.