Prevent Sweetalert to Be Closed on Clicking Outside the Popup Window

SweetAlert2 disallow outside click after confirm

It's possible to pass the function to the allowOutsideClick parameter:

allowOutsideClick: () => { 
// add your logic here and return boolean
}

Your case:

Swal.fire({
title: 'Submit email to run ajax request',
input: 'email',
showLoaderOnConfirm: true,
preConfirm: (email) => {
return new Promise((resolve) => {
setTimeout(() => {
resolve()
}, 3000)
})
},
allowOutsideClick: () => !swal.isLoading()
})
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

Cannot prevent sweet alert from closing

Here's an example that's fully functional (for solving your specific problem):

<html>
<body>
<div class="showDialogButton">Show dialog</div>

<script src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@8"></script>
<script type="text/javascript">

$(() => {

const title = "Hi"
const template = `<b>hello</b> world`

$(".showDialogButton").click(() => {
Swal.fire({
title: title,
html: template,
preConfirm: function (email) {
email = '';
return new Promise(function (resolve, reject) {
setTimeout(function () {
if (email === '') {

reject('Email is empty!')

} else {

resolve()
}
}, 1000)
}).catch(err => {
alert(`error: ${err}`)
return false
})
},
});
})
})
</script>
</body>
</html>

The default behavior is to close the dialog. In order to override that, you have to return false from the function that you're passing in to .catch.

From https://sweetalert2.github.io/#configuration

Argument: preConfirm

Default value: null

Description: Function to execute before confirm, may be async (Promise-returning) or sync. Returned (or resolved) value can be:

  • false to prevent a popup from closing
  • anything else to pass that value as the result.value of Swal.fire()
  • undefined to keep the default result.value

JavaScript sweetAlert popup closes itself after a quick second

Looks like it's a form submit, So when you click the button the page refreshes.That's why you see the alert for a second and it hides.

<button class="btn btn-success" type="submit" name="submit" onclick="myFunction()">Submit</button>

You must change the button type to be button.

   <button class="btn btn-success" type="button" onclick="myFunction()">Submit</button>

SweetAlert open another alert with prevent closing previous alert

It is not possible to show more than one modal at a time, by design.

SweetAlert open another alert with prevent closing previous alert

Show two swal at same time

2 or more modals at the same time



Related Topics



Leave a reply



Submit