I am trying to add validation to a multiple-input modal I set up with SweetAlert2.
I am using the below code, modified from https://sweetalert2.github.io/#multiple-inputs
jQuery('body').on('click', '#feedback', async function () {
const {value: feedback} = await swal.fire ({
title: 'Send us your feedback!',
showCancelButton: true,
confirmButtonText: 'Submit',
denyButtonText: 'Cancel',
customClass: {
content:'full-width'
},
html:
'<input id="ratingValue" type="text" />'+
'<input id="topicValue" type="text" />'+
'<input id="comment" type="text" />'
,
preConfirm: () => ({
rating: jQuery('#ratingValue').val(),
topic: jQuery('#topicValue').val(),
comment: jQuery('#comment').val()
})
}).then((result) => {
console.log(JSON.stringify(feedback));
if(feedback.rating != "" && feedback.topic != ""){
Swal.fire('Submitted!', '', 'success')
}
});
Obviously, I have a problem, I am passing the feedback object as a pass by promise parameter, so I can't try to call it from the (then) state as the variable hasn't been initialised yet and I get an error. Is there any workaround for this? I would like to validate my inputs before submitting, and be able to allow the user to correct himself.
Thanks a lot!
.on('click' takes a callback function, it doesn't return a Promise, so you can't simply chain .then() to it. You can do something like this, I guess :
jQuery('body').on('click', '#feedback', clickHandler);
const clickHandler = async () => {
const feedback = await swal.fire({...});
console.log(JSON.stringify(feedback));
if (feedback.rating != "" && feedback.topic != "") {
Swal.fire('Submitted!', '', 'success')
}
}