I'm trying to create a step by step form using SweetAlert2, and I need to be able to add an extra step in my chaining based on an if statement.
For example, on my third modal I may have a radio question that says 'Will you be bringing a plus 1?', and if the user selects 'true' I need it to pop up with a extra stage asking 'name of plus one', if the user selects false then just continue.
swal.mixin({
confirmButtonText: 'Next →',
showCancelButton: true,
progressSteps: ['1', '2', '3', '4']
}).queue([
{
title: 'Which event?',
text: 'Please start by selecting the event you would like to book in!',
input: 'select',
inputClass: 'swal-select-event',
inputPlaceholder: 'Please Select',
inputOptions: {
'1' : 'Dance Event',
'2' : 'Football Event'
},
inputValidator: (value) => {
return new Promise((resolve) => {
if (value === '') {
resolve('You need to select an event!')
} else {
resolve()
}
})
}
},
{
title: 'What Day?',
text: 'Which day are they due to come in?',
html:'<input id="swal-booking-date-select" type="date"/>',
preConfirm: () => {
return document.getElementById('swal-booking-date-select').value
},
inputValidator: (value) => {
return new Promise((resolve) => {
if (value === '') {
resolve('You need to select a date!')
} else {
resolve()
}
})
}
},
{
title: 'Plus one?',
text: 'Will you be bringing a plus one with you?',
input: 'radio',
inputOptions: {
'yes' : 'Yes',
'no' : 'No'
},
inputValidator: (value) => {
return new Promise((resolve) => {
if (value === null) {
resolve('I need to know if you will be bringing a plus 1!')
} else if(value === 'yes') {
//EXTRA STAGE GOES HERE TO GET PLUS ONE NAME
} else {
resolve()
}
})
}
},
{
title: 'What else?',
input: 'text',
text: 'Any other information that needs noting for this booking?'
}
]).then((result) => {
if (result.value) {
//Do something with all of the data here
}
})
Does anyone know if this is possible?
A way would be to use a simple Swal instance for that extra optionnal step... And to keep the value in an aside variable declared globally.
var plus1name="";
In the sake of clarity, I won't repeat all your code, since unchanged. Here is a new part to add:
//EXTRA STAGE GOES HERE TO GET PLUS ONE NAME
swal({
title:"Plus one!",
text:"What is his/her name?",
input:"text"
}).then(function(value){
plus1name = value;
resolve();
});
Then in the .then(result)
part:
//Do something with all of the data here
swalResults = result.value;
swalResults.push(plus1name.value)
console.log(swalResults);
So you have an array with all the answers. The extra question was pushed at the end of it, so the order in the array is not the order of asking...
I worked on it on CodePen.