Uncaught SweetAlert: Unexpected 2nd argument? - javascript

I have a problem with sweetalert, I would like to show the confirm box alert on button click but it's not working
This is my JS code:
$(document).ready(function(){
$('[data-confirm]').on('click', function(e){
e.preventDefault(); //cancel default action
//Recuperate href value
var href = $(this).attr('href');
var message = $(this).data('confirm');
//pop up
swal({
title: "Are you sure ??",
text: message,
type: "warning",
showCancelButton: true,
cancelButtonText: "Cancel",
confirmButtonText: "confirm",
confirmButtonColor: "#DD6B55"},
function(isConfirm){
if(isConfirm) {
//if user clicks on "confirm",
//redirect user on delete page
window.location.href = href;
}
});
});
});
HTML:
<a data-confirm='Are you sure you want to delete this post ?'
href="deletePost.php?id=<?= $Post->id ?>"><i class="fa fa-trash">
</i> Delete</a>
All required files are imported.

The code you are using is from prior the latest version 2. Please read up on Upgrading from 1.X.
You should use promise to keep track of user interaction.
Updated code
$(document).ready(function(){
$('[data-confirm]').on('click', function(e){
e.preventDefault(); //cancel default action
//Recuperate href value
var href = $(this).attr('href');
var message = $(this).data('confirm');
//pop up
swal({
title: "Are you sure ??",
text: message,
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
swal("Poof! Your imaginary file has been deleted!", {
icon: "success",
});
window.location.href = href;
} else {
swal("Your imaginary file is safe!");
}
});
});
});
Notes
type have been replaced with icon option.
Replaced showCancelButton, CancelbuttonText, confirmButtonText and confirmButtonColor with only buttons.
dangerMode: true to make the confirm button red.

Related

Bootstrap 5 Modal & jQuery - centered spinner take time to show up before content loading

I have a bootstrap 5 modal with some specific functionality in jQuery a centered spinner shows up in the modal before loading the content here is a live example from here.
the issue that I have is the spinner take time when the modal opened to show up before loading content to know more about what I'm talking about trying to view the example link
while I click to button the spinner does not show up fast it displays the content first and secondly the spinner and this it's not correct.
Live Example: https://codepen.io/themes4all/pen/vYmeXpy
jQuery Code:
(function ($) {
"use strict";
$(window).on("load", function () {
if ($(".modal").length) {
$(".modal").modal("show");
$(".modal").on("shown.bs.modal", function (e) {
e.preventDefault();
$(".spinner")
.removeClass("d-none")
.delay(3000)
.fadeOut(500, function () {
$(this).addClass("d-none");
});
return false;
});
$(".btn-close").on("click", function (e) {
e.preventDefault();
var swalWithBootstrapButtons = Swal.mixin({
customClass: {
confirmButton: "btn btn-primary",
cancelButton: "btn btn-danger me-3",
},
buttonsStyling: false,
});
swalWithBootstrapButtons
.fire({
title: "Are you sure?",
text: "You won't be able to revert this!",
icon: "warning",
confirmButtonText: "<i class='fas fa-check-circle me-1'></i> Yes, I am!",
cancelButtonText: "<i class='fas fa-times-circle me-1'></i> No, I'm Not",
showCancelButton: true,
reverseButtons: true,
focusConfirm: false,
})
.then((result) => {
if (result.isConfirmed) {
$(".modal").modal("hide");
}
});
return false;
});
}
});
})(window.jQuery);
Live example
What you are doing right now is trying to remove class .d-none (display: none!important) on the spinner, which is working slower than content loading. What you should do is the opposite thing: the spinner should be shown by default and you need to hide it when content loads. So, you need to remove all classes with the display !important (d-flex, d-none), need to hide spinner on content load and need to show it back on modal close.
Added CSS:
.spinner {
display: flex;
}
jQuery:
(function ($) {
"use strict";
$(window).on("load", function () {
if ($(".modal").length) {
$(".modal").modal("show");
$(".modal").on("shown.bs.modal", function (e) {
e.preventDefault();
$(".spinner")
.delay(3000)
.fadeOut(500);
return false;
});
$(".btn-close").on("click", function (e) {
e.preventDefault();
var swalWithBootstrapButtons = Swal.mixin({
customClass: {
confirmButton: "btn btn-primary",
cancelButton: "btn btn-danger me-3",
},
buttonsStyling: false,
});
swalWithBootstrapButtons
.fire({
title: "Are you sure?",
text: "You won't be able to revert this!",
icon: "warning",
confirmButtonText: "<i class='fas fa-check-circle me-1'></i> Yes, I am!",
cancelButtonText: "<i class='fas fa-times-circle me-1'></i> No, I'm Not",
showCancelButton: true,
reverseButtons: true,
focusConfirm: false,
})
.then((result) => {
if (result.isConfirmed) {
$(".modal").modal("hide");
$(".spinner").delay(1000).show(100);
}
});
return false;
});
}
});
})(window.jQuery);

I want add a window Alert before I reset the style I already use?

I have a button here with a simple CSS. what I want is, when I hit on that button to reset my style. I use it, I need to add a sweet alert before pressing the button.
<button class="reset-option">Reset Options</button>
document.querySelector(".reset-option").onclick = function () {
localStorage.clear();
window.location.reload();
};
What I want is, add this alert to handle it with javascript.
swal({
title: "OOPS !",
text: "You Want To Resat Your Style!",
icon: "warning",
});
I tried to do this but it didn't work.
let resetOption = document.querySelector(".reset-option");
resetOption.onclick = function () {
if (resetOption.window === reload()) {
swal({
title: "OOPS !",
text: "You Want To Resat Your Style!",
icon: "warning",
});
}
}
You can have only one onclick handler per element. So here, the second overwrites the first.
Also, Swal returns a promise to handle the result. What is below is real close to the example found here.
I suggest:
document.querySelector(".reset-option").onclick = function () {
swal.fire({
title: "OOPS !",
text: "You Want To Resat Your Style!",
icon: "warning",
showCancelButton: true
}).then((result) => {
if (result.isConfirmed) {
console.log("confirmed");
//localStorage.clear();
//window.location.reload();
}else{
console.log("canceled")
}
})
};
<link href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/10.12.5/sweetalert2.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/10.12.5/sweetalert2.min.js"></script>
<button class="reset-option">Reset Options</button>
if you want to show an alert to user before hit the button, you can add mouse hover event to your button.
var event = new MouseEvent('mouseover', {
'view': window,
'bubbles': true,
'cancelable': true
});
document.querySelector(".reset-option").onclick = function () {
localStorage.clear();
window.location.reload();
};
var cc=document.querySelector(".reset-option")
cc.addEventListener('mouseover', function() {
//your alert code here
alert('Before hit button');
});

Prevent Page navigation - SweetAlert

I'm trying to replace the JS box dialog with sweet alert dialog box.
At normal cases, it works perfectly.
But, at the time of navigating the page on confirmation. It didn't work.
JS box :
var confirm = window.confirm("Warning! You may have unsaved data,it will be lost..!" + "\n" + "Are you sure want to leave this page ?");
if (confirm) {
$scope.$eval(event); //It prevents the page to nav ,until i confirm it.
} else {
event.preventDefault();
}
It works.
In case of sweetalert, I'm using the same scenario
$scope.validation = function(event) {
//....
sweetAlert({
title: "Are you sure?", //Bold text
text: "Your will not be able to recover this imaginary file!", //light text
type: "warning", //type -- adds appropiriate icon
showCancelButton: true, // displays cancel btton
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm) {
//Function that triggers on user action.
if (isConfirm) {
$scope.$eval(event); //????
/* sweetAlert(
'Deleted!',
'Your file has been deleted.',
'success'
)*/
} else {
event.preventDefault();
}
}
For state change ,
.state('ModuleName',{
url : '/ModuleName',
templateUrl : 'ModuleMenu/ModuleName.html',
controller : 'modulectrl',
resolve : {
loadPlugin : function($ocLazyLoad) {
return $ocLazyLoad
.load([
{
name : 'css',
insertBefore : '#app-level',
files : [
'../static/vendors/bower_components/nouislider/jquery.nouislider.css',
]
},
{
name : 'vendors',
files : [
'../static/vendors/bower_components/angular-farbtastic/angular-farbtastic.js' ]
},
{
name : 'ComliveApp',
files : [ '../static/scripts/controller/modulectrl.js' ]
} ])
}
}
})
On href,the respective view is loaded. My point is that page should not be loaded until sweetAlert confirms it.
Suggestions/answers are appreciated.
Thanks.

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.
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;
}
});
});

Bootstrap 3 tabs preventDefault

I am trying to build what seems to be simple jquery script. Once form input has been changed and user wants to leave page without saving, he will be prompted to confirm leaving. Everything works ok on regular anchors, but I can't get event.preventDefault working on Bootstrap 3 tabs. Any ideas? Thank you.
My current (beta) script:
//Confirm on exit when form has changed
var show_exit_error = 1;
$("form.check-on-exit").one("change", ":input", function() {
show_exit_error = 1;
$(document).on('click', 'a', function(e) {
if (show_exit_error == 1) {
$link = $(this);
e.preventDefault();
swal({
title: "Do you really want to leave?",
text: "",
type: "warning",
showCancelButton: true,
cancelButtonText: "Leave",
confirmButtonColor: "#18a689",
confirmButtonText: "No",
closeOnConfirm: true,
closeOnCancel: true,
}, function(isConfirm){
if(!isConfirm) {
show_exit_error = 0;
window.location = $link.attr('href');
}
});
}
});
Demo: http://codepen.io/anon/pen/bdzyRy?editors=101
Try to edit one of inputs and then switch to tab2. It ignores prevetndefault and switch tab. I need script to switch tab only if user click on No.
Here is simple workaround:
//Confirm on exit when form has changed
var show_exit_error = 1;
$("form.check-on-exit").one("change", ":input", function() {
show_exit_error = 1;
$('.tabs-container').find('a[data-toggle="tab"]').attr('data-toggle', 'notab');
$(document).on('click', 'a', function(e) {
if (show_exit_error == 1) {
$link = $(this);
e.preventDefault();
swal({
title: "Do you really want to leave?",
text: "",
type: "warning",
showCancelButton: true,
cancelButtonText: "Leave",
confirmButtonColor: "#18a689",
confirmButtonText: "No",
closeOnConfirm: true,
closeOnCancel: true,
}, function(isConfirm){
if(!isConfirm) {
show_exit_error = 0;
if ($link.attr('data-toggle') == 'notab') {
$('.tabs-container').find('a[data-toggle="notab"]').attr('data-toggle', 'tab');
$link.trigger('click');
} else {
window.location = $link.attr('href');
}
}
});
}
});
I assume the tabs you're referring to are anchors to external documents. Since you leave the page at that moment, it would last to remove the Bootstrap click handler completely.
$(function() {
// remove the click.bs.tab.data-api handler from all tabs with class .external-tabs
$('.external-tabs').off('click.bs.tab.data-api');
});
As an alternate solution you could just remove the data-toggle="tab" attribute from the item, since this is the selector for adding the handler in Bootstrap.

Categories