簡體   English   中英

SweetAlert2 添加動態選項到 select 輸入

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM