This question already has answers here:
How to have sweetalert return true/false for confirm without promise?
(4 answers)
Closed last month.
Here is my code where i am using sweetalert latest code for showing up a confirmation just like a javascript confirm box to act if ok, is pressed adn if its a cancel, do nothing,
Here is my try and my original code
var rtrnval = swal({
title: "Check!",
text: "You must select a task before entering hours.",
type: "warning",
showCancelButton: true,
confirmButtonColor: "##DD6B55",
confirmButtonText: "Confirm",
closeOnConfirm: false
}, function(isConfirm){
return isConfirm; //Will be either true or false
});
alert(rtrnval); return;
my original code is like this
var rtrnval = confirm("You must select a task before entering hours.");
it is not showing the sweetalert box when i change confirm to swal, it throws error on the function but when i use confirm, the function works properly,
i am unable to read the value being returned to me like true/false so i ca act upon it
any guidance, greatly appreciated
i already posted code what i tried
here is what i want to replace
function ConfirmDelete(id){
var rtrnval = confirm("are you sure!!");
if (rtrnval == 1)
{
location='page2.php='+id
}
return 0
}
and some cases i am doing this
return confirm("are you sure")
Try this:
Swal.fire({
title: "Check!",
text: "You must select a task before entering hours.",
type: "warning",
showCancelButton: true,
confirmButtonColor: "##DD6B55",
confirmButtonText: "Confirm",
closeOnConfirm: false
}).then((result) => {
if (result.isConfirmed) {
console.log('Confirmed');
} else if (result.isDenied) {
console.log('Canceled');
}
})
Related
i have a form and a complex validation Javascript which part of it is the following simplified code:
if (Condition1 Meets criteria){
Swal.fire({ //Cancel if Condition 1 Meets Criteria
title: 'Validation Problem',
icon: 'error',
html: 'Form wont be submited because <b>Condition 1 met criteria</b>',
showCloseButton: false,
focusConfirm: false,
confirmButtonText: 'Return'
})
return false; //Prevent submit form
}else if (Condition2 Meets criteria){
Swal.fire({ //Warning msg if Condition 2 Meets Criteria
title: 'Warning msg..',
icon: 'warning',
html: 'Condition 2 meets criteria </br>'+
'Are you sure you want to continue ?',
showCloseButton: false,
focusConfirm: false,
reverseButtons: true,
cancelButtonText: 'Cancel',
confirmButtonText: 'Continue'
}).then((result) => {
if (result.isConfirmed) {
alert ("Continue to next Rule!");
return true; //User confirmed to continue, Procceed to Validation 3 Rule...
}else{
alert ("Stop Submit Form!");
return false; //Dont submit Form
}
})
}else if (Condition3 Meets criteria){
...........
}
Condition 1 works good, Condition 2 ignores the msg the user will press . What am I doing wrong ?
Simple alerts do show up so condition is met, but if I will comment the Alerts, system doesnt go on to return functionalities...
I am using this jquery repeater.
I am using custom calculations on each addition of form, say multiplying one input with another, and then making a total of multiplication results.
Problem is when we click on delete, it just hides the row but don't delete values of the item,
When we delete one more item, then it will delete the first item which was hidden and my calculation is get updated.
I check the number of class on delete of item, it does not reduce on first delete, it always reduces on the second delete,
How to completely delete the row with its values?
var _CalTotal = function () {
console.log($(".billitem_quantity").length );
//Calculate total of quantity
var total_quantity = 0;
$(".billitem_quantity").each(function(){
total_quantity += parseFloat($(this).val());
});
$('#itemquantity_total').val(total_quantity.toFixed(2));
**//Calculate total of amount**
var total_amount = 0;
$(".billitem_total").each(function(){
total_amount += parseFloat($(this).val());
});
$('#bill_total').val(total_amount.toFixed(2));
console.log('test');
}
Below is code for hide,
hide: function(deleteElement) {
Swal.fire({
title: "Are you sure to cancel this order?",
text: "You will not able to revert this",
icon: "question",
showCancelButton: true,
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, revert it!",
reverseButtons: true,
}).then(function(result) {
if (result.value) {
$(this).slideUp(deleteElement);
//I guess something is missing here to delete that item with first delete fire.
_CalTotal(); //Here i am calling calltotal function.
} else if (result.dismiss === "cancel") {
}
});
},
After some debugging I found that setting a setTimeout() of 1 second removed your issue. This means some code is asynchronously processed in the background. Therefore you need a callback function or a promise.
You can do it like this by adding to the slideUp() callback function:
hide: function(deleteElement) {
Swal.fire({
title: "Are you sure to cancel this order?",
text: "You will not able to revert this",
icon: "question",
showCancelButton: true,
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, revert it!",
reverseButtons: true,
}).then(function(result) {
if (result.value) {
$(this).slideUp(function(){
deleteElement();
_CalTotal();
);
} else if (result.dismiss === "cancel") {
}
});
},
I got the solution from this question (not the accepted answer).
I am working on a drag and drop list, I need that every time you try to move an item on the list ask if you really want to move it, if so, make the move, if not, return it to its initial position.
function handleDragEnd(e) {
swal({
title: "Are you sure?",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#f8c286",
confirmButtonText: "Accept",
cancelButtonText: "Cancel",
html: true
},
function(isConfirm){
if (isConfirm) {
e.target.classList.remove('over');
var start = $("#"+e.target.id).prev().attr('id');
var end = $("#"+e.target.id).next().attr('id');
Calculate(start,e.target.id,end,data);
swal("Successfull","change made", "success");
} else {
this.ondragexit;
}
});
But I have errors in both cases, when it's affirmative, I get error in the remove
And when I don't want to move it, he lets me do it anyway.
How can it be corrected to work properly?
Could you help me, please?
I am trying to delay a SweetAlert popup to not display for a few seconds once it has been triggered.
e.g. User performs action on webpage to trigger SweetAlert, but instead of displaying instantly, it wait 2 seconds and then displays. - I've been researching various ways to do this, but no luck...I think maybe setTimeout is needed?
Here is my SweetAlert function which is working so far:
if( response == 10 ){
swal({
type: 'success',
title: 'YOUR BALANCED BOX IS FULL',
text: 'Youve added the recommended amount of items for your plan!',
allowOutsideClick: false,
showCancelButton: true,
cancelButtonText: "Modify Selection",
cancelButtonColor: '#d33',
showConfirmButton: true,
confirmButtonColor: '#61ce70',
confirmButtonText: "Proceed To Cart",
}).then((result) => {
if (result.value) {
window.location = "/basket/";
}
})
}
Any help appreciated!
SPECIFIC SWEETALERT 2 ANSWER:
Above code logic answer from Leo is correct. Am sharing the final version with SweetAlert 2 with setTimeout as a function added to delay the popup from opening.
The setTimeout function wraps around the entire SweetAlert 2 function and the timer is set at the bottom of the end of the function (in this case to 3000).
Hope this helps anyone looking to do the same!
setTimeout(function(){swal({
type: 'success',
title: 'YOUR BALANCED BOX IS FULL',
text: 'Youve added the recommended amount of items for your plan!',
allowOutsideClick: false,
showCancelButton: true,
cancelButtonText: "Modify Selection",
cancelButtonColor: '#d33',
showConfirmButton: true,
confirmButtonColor: '#61ce70',
confirmButtonText: "Proceed To Cart",
}).then((result) => {
if (result.value) {
window.location = "/basket/";
}
})},3000);
Yes indeed you can use setTimeout to achieve this easily, i set up a simple snippet so you can try it out!
// When button gets clicked.
$("#button").click(() => {
// Instantely change it's text to loading..
$("#button").text("Loading!");
// Wait 2kms then change the text to Done!
setTimeout(() => {
$("#button").text("Done!");
}, 2000);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">Event</button>
-Leo
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.
how-to-use-confirm-using-sweet-alert
how-to-run-a-sweetalert-instead-of-default-javascript-confirm-method
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?
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.
var prev_val;
$('#' + dropdownId).focus(function() {
prev_val = $(this).val();
}).change(function(e) {
$(this).blur();
var self = this;
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) {
// preventDefault is useless since change event has already happened
// if Confirm is true then do nothing else
// change with prev val
//e.preventDefault();
return true;
} else {
// this here does not refer the dom element
// it might be changed because it is called through the swal library code at a later time, use self which is declared out of the callback context.
$(self).val(prev_val);
return false;
}
});
});