davidsneal
davidsneal

Reputation: 138

SweetAlert with type of "input" still runs if user clicks cancel

So I'm using SweetAlert, and am offering the opportunity to add an extra short message to a user's request. The problem I have is that even if the user clicks the 'Cancel' button, it still makes the post request (removed from the example below) within the function().

swal({
    title: "Request!",
    text: "Add a message to your request if you wish...",
    type: "input",
    showCancelButton: true,
    closeOnConfirm: false,
    closeOnCancel: true,
    inputPlaceholder: "Short message..."
}, function(inputValue) {
   // this is always run, regardless of if the user clicks cancel
});

I could probably workaround this by forcing a message to be entered, then I can wrap the post request in an if statement on the inputValue value, however this must be optional.

Please also note that I'd prefer to stick to the version of SweetAlert that I linked to above.

Upvotes: 0

Views: 604

Answers (1)

Michael Coker
Michael Coker

Reputation: 53674

The inputValue parameter that the callback takes is false if the user hits cancel, and true if they don't. So the way to disable the callback if the user hits cancel is to check for the existence of inputValue in the callback.

swal({
    title: "Request!",
    text: "Add a message to your request if you wish...",
    type: "input",
    showCancelButton: true,
    closeOnConfirm: false,
    closeOnCancel: true,
    inputPlaceholder: "Short message..."
}, function(inputValue) {
   if (inputValue) {
      // the user didn't hit cancel
   }
});

Upvotes: 2

Related Questions