Jaims Jaims - 6 months ago 37
jQuery Question

Wait on SweetAlert response

I currently have a function that asks the user for confirmation when changing a value in a dropdown. This works fine using the standard

JavaScript
confirm()
. Here's the fiddle.

var prev_val;
$('#dropdownId').focus(function () {
prev_val = $(this).val();
}).change(function () {
$(this).blur();
var success = confirm('Are you sure you want to change the Dropdown?');
if (success) {
// Proceed as normal.
} else {
// Reset the value & stop normal event
$(this).val(prev_val);
return false;
}
});


But when using
SweetAlert
, the change event always takes place before I'm able to confirm/cancel. Meaning, when I select a new value, and pressing "cancel", it does not stop the event and reset the previous value. Which it does with the regular
JavaScript
confirm
dialog.

var prev_val;
$('#' + dropdownId).focus(function () {
prev_val = $(this).val();
}).change(function (e) {
$(this).blur();
return swal({
title: "Are you sure?",
text: "Do you want to change the dropdown?",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes",
cancelButtonText: "No",
closeOnConfirm: true,
closeOnCancel: true
},
function (isConfirm) {
if (isConfirm) {
e.preventDefault();
return true;
} else {
$(this).val(prev_val);
return false;
}
});
});


It might also be interesting to note that this
JavaScript
might even be invalid (pretty new to
JavaScript
), e.g. returning from the
confirm
function and from the
swal
function not functioning.

However, after Googling around, I found people with similar issues.



But that seems a bit hacky since it's preventing any action, but when selecting confirm he re-creates the function that should have been called by default. Which seems like quite a hack for something so simple.

Any possibility of the
SweetAlert
just acting like a regular
confirm
dialog?

Answer

The value does not get set back because this in swal is not the select, but the sweet alert dialog. So in your change event you have to define a variable that holds the changed select element and use it to set the value back when the user clicks 'No'.

.change(function(e) {
    var select = this; // save select element to variable

    $(this).blur();
    return swal({
        title: "Are you sure?",
        text: "Do you want to change the dropdown?",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Yes",
        cancelButtonText: "No",
        closeOnConfirm: true,
        closeOnCancel: true
    },
    function(isConfirm) {
        if (isConfirm) {
            e.preventDefault();
            return true;
        } else {
            $(select).val(prev_val); // use select reference to reset value
           return false;
        }
    });
});

You can find a working example in this fiddle.