SweetAlert dropdown dynamically add items in list
jquery, json, sweetalert
Solution
As the SweetAlert2 documentation says, `inputOptions` parameter can be `object` or `Promise`.
To populate select items dynamically you should use promises, here's the simple example:
var inputOptionsPromise = new Promise(function (resolve) {
// get your data and pass it to resolve()
setTimeout(function () {
resolve({
'#FF0000': 'Red',
'#00FF00': 'Green',
'#0000FF': 'Blue'
})
}, 2000)
})
Swal.fire({
input: 'select',
inputOptions: inputOptionsPromise
})
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
Notice, that SweetAlert2 will automatically show a loader until the Promise for `inputOptions` parameter will be resolved or rejected.
Problem
I am currently using sweetalert2 to capture user's input from the dialog. I would like to use the dropdown in chaining queue dialog but I can't seem to find a way to dynamically add items in the dropdown list. Let's say I want to retrieve data from JSON format and place in the dropdown list, is there a way to do it? ``` function userInput() { swal.setDefaults( { showLoaderOnConfirm: true, confirmButtonText: 'Next →', showCancelButton: true, animation: true, progressSteps: ['1', '2', '3'] } ); var steps = [ { text: 'Select an author to analyze the commit', input: 'select', inputOptions: { 'SRB': 'Serbia', // How do I dynamically set value? 'UKR': 'Ukraine', 'HRV': 'Croatia' } }, { text: 'Select multiple authors to compare their commits', input: 'select', inputOptions: { 'SRB': 'Serbia', // How do I dynamically set value? 'UKR': 'Ukraine', 'HRV': 'Croatia' } }, { text: 'Select a file directory to analyze all author\'s commit', input: 'select', inputOptions: { 'SRB': 'Serbia', // How do I dynamically set value? 'UKR': 'Ukraine', 'HRV': 'Croatia' } } ]; swal.queue(steps).then(function(result) { swal.resetDefaults(); swal({ type: 'success', title: 'Success', text: 'Scroll down for statistics!', html: 'Your selections: <pre>' + JSON.stringify(result) + '</pre>', confirmButtonText: 'Ok', showCancelButton: false }) }, function() { swal.resetDefaults() }) } ``` Retrieve data in JSON format: ``` function getData(repolink) { readDataFromGit('https://api.github.com/repos/' + repolink + '/git/trees/master?recursive=1', function(text){ data = JSON.parse(text); $.each(data, function(i, v) { // Retrieve v.login data! data = v.login; }) }); } function readDataFromGit(link, callback) { var request = new XMLHttpRequest(); request.overrideMimeType("application/json"); request.open('GET', link, true); request.onreadystatechange = function() { if (request.readyState === 4 && request.status == "200") { callback(request.responseText); } }; request.send(null); } ```