Timer with confirm and cancel button - javascript

i'm a noobs at sweet alert.
Is it possible to create a sweet alert prompt which has confirm button, cancel and timer.
The logic is if the alert not confirmed, timer automatically execute the same function with cancel. I have tried and stuck. even if the alert confirmed, the timer still counting and the the cancel function is called.
sweetAlert({
title: 'Stay in fullscreen',
text: "You will be logged out in 10 seconds or if you leave the fullscreen!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#ff0000',
confirmButtonText: 'Go fullscreen!',
cancelButtonText: 'Leave this page!',
confirmButtonClass: 'btn btn-success',
cancelButtonClass: 'btn btn-warning',
closeOnConfirm: 'true',
timer:'10000',
buttonsStyling: false
},function(isConfirm) {
if (isConfirm) {
return launchIntoFullscreen(document.documentElement) // timer still still counting
} else {
return Redirect()
}
}).then(function () {
swal(
window.alert('teest')
)
}, function (dismiss) {
// dismiss can be 'cancel', 'overlay',
// 'close', and 'timer'
if (dismiss === 'timer') {
return Redirect()
}
})

Checking the isConfirm argument for null should tell you if the callback was initialized by the timer finishing.
swal({
title: "Auto close alert!",
text: "I will close in 2 seconds.",
timer: 2000,
showConfirmButton: true,
showCancelButton: true
},
function(isConfirm) {
if (isConfirm === null || isConfirm == false)
cancelFunction();
else
confirmFunction();
}
);
As far as I could find, this behavior is not documented, but I believe this is the relevant bit of the source

swal({
title: "Auto close alert!",
text: "I will close in 2 seconds.",
timer: 2000,
showConfirmButton: true,
showCancelButton: true
},
function(isConfirm) {
if (isConfirm === null || isConfirm == false)
cancelFunction();
else
confirmFunction();
}
);
the code above still execute cancelFunction();
i add a line before Confirmfunction.
if (isConfirm !=null && isConfirm != false) {
closeInSeconds = Number.MAX_VALUE/1000; // this line extends timer time
document.documentElement);
}
else {
Redirect();
}

Related

allowOutsideClick not working in SweetAlert2

function show_alert(args) {
Swal.fire({
icon: args.icon,
title: args.title,
text: args.message,
html: args.html,
allowEscapeKey: args.allowEscapeKey ? args.allowEscapeKey : true,
allowOutsideClick: args.allowOutsideClick ? args.allowOutsideClick : true,
confirmButtonText: args.confirmButtonText ? args.confirmButtonText : 'Tamam',
confirmButtonColor: args.confirmButtonColor ? args.confirmButtonColor : '#3085d6',
cancelButtonText: args.cancelButtonText ? args.cancelButtonText : 'İptal',
cancelButtonColor: args.cancelButtonColor ? args.cancelButtonColor : '#d33',
showCancelButton: args.showCancelButton === undefined ? false : args.showCancelButton,
showCloseButton: args.showCloseButton === undefined ? false : args.showCloseButton,
showConfirmButton: args.showConfirmButton === undefined ? true : args.showConfirmButton,
didOpen: args.didOpen ? args.didOpen : null,
reverseButtons: true,
}).then((result) => {
if (result['isConfirmed']) {
args.callback ? args.callback_args ? args.callback(args.callback_args) : args.callback() : null;
} else if (result['isDismissed'] && args['isDismissed']) {
event.preventDefault();
args.isDismissed ? args.isDismissed() : null;
}
});
}
The above code block is a general alert display function. I can display alerts based on the parameters I give in "args".
I wrote the following code blocks to show a loading alert when the user clicks a button:
show_alert({
'title': 'Please wait',
'html': 'Loading audio file ...',
'allowEscapeKey': false,
'allowOutsideClick': false,
'showConfirmButton': false,
'showCancelButton': false,
'showCloseButton': false,
'didOpen': () => {Swal.showLoading();},
'isDismissed': () => {console.log('dismissed');}
});
However, when the user clicks anywhere on the page outside of the alert, the alert closes.
Is it possible to stop this by using a function like event.preventDefault()? If you can help, I would appreciate it.
In the "else if" block, I tried to catch the event and prevent the click event, like the "allowOutsideClick" property, but I couldn't.
You ternary always sets allowOutsideClick to a truthy value:
allowOutsideClick: args.allowOutsideClick ? args.allowOutsideClick : true
This needs to be changed to false if allowOutsideClick is falsy:
allowOutsideClick: args.allowOutsideClick ? args.allowOutsideClick : false
As SweetAlert accepts truthy/falsy values for its options, this can be simplified to just:
allowOutsideClick: args.allowOutsideClick
I would recommend looking at your other options and providing similar optimisations. Such as with the allowEscapeKey option (which seems to have a similar issue).
Also, anywhere that you have the pattern of:
a ? a : b
can be simplified to just
a || b
As these mean the same thing.
function show_alert(args) {
Swal.fire({
icon: args.icon,
title: args.title,
text: args.message,
html: args.html,
allowEscapeKey: args.allowEscapeKey,
allowOutsideClick: args.allowOutsideClick,
confirmButtonText: args.confirmButtonText || 'Tamam',
confirmButtonColor: args.confirmButtonColor || '#3085d6',
cancelButtonText: args.cancelButtonText || 'İptal',
cancelButtonColor: args.cancelButtonColor || '#d33',
showCancelButton: args.showCancelButton,
showCloseButton: args.showCloseButton,
showConfirmButton: args.showConfirmButton === undefined ? true : args.showConfirmButton,
didOpen: args.didOpen,
reverseButtons: true,
}).then((result) => {
if (result['isConfirmed']) {
args.callback ? args.callback_args ? args.callback(args.callback_args) : args.callback() : null;
} else if (result['isDismissed'] && args['isDismissed']) {
event.preventDefault();
args.isDismissed ? args.isDismissed() : null;
}
});
}
show_alert({
'title': 'Please wait',
'html': 'Loading audio file ...',
'allowEscapeKey': false,
'allowOutsideClick': false,
'showConfirmButton': false,
'showCancelButton': false,
'showCloseButton': false,
'didOpen': () => {
Swal.showLoading();
},
'isDismissed': () => {
console.log('dismissed');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/11.6.16/sweetalert2.min.js" integrity="sha512-4aFcnPgoxsyUPgn8gNinplVIEoeBizjYPTpmOaUbC3VZQCsRnduAOch9v0Pn30yTeoWq1rIZByAE4/Gg79VPEA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/11.6.16/sweetalert2.css" integrity="sha512-JzSVRb7c802/njMbV97pjo1wuJAE/6v9CvthGTDxiaZij/TFpPQmQPTcdXyUVucsvLtJBT6YwRb5LhVxX3pQHQ==" crossorigin="anonymous" referrerpolicy="no-referrer"/>
As a side note, you're misusing the conditional operator ? : within your .then(). You should use these when you need to use the return value that the expression evaluates to. When you don't use the evaluated value, and instead just perform side-effects, such as calling a function, then you're better off using an if-statement.
I'd also argue that only calling args.callback(args.callback_args) only when args.callback_args is truthy probably isn't what youu want to do, as this prevents you from being able to specify callback_args as falsy values such as false, 0, "", etc. You're better of always calling args.callback(args.callback_args)

How do I show one swal at the time in javascript

I created a swal for a notification. To show up in the screen the result of the ajax function has to be 0. But this ajax function run every 2 seconds. Sometimes the ajax function returns more than one result has 0, so the swal dont stop showing, just showing the other when the user click in the close button. I would like to show one swal at the time, but setInterval function isnt alowing me to do it.
This is the funtion with the swal:
function montarModalLigacao(cdRamalLigacao = null)
{
var dsHtml = buscaDadosAjax('Ramal', 'obtemHtmlLigacao', {cdLigacaoRamal: cdRamalLigacao});
console.log(dsHtml);
if (dsHtml)
{
swal({
allowOutsideClick: false,
allowEnterKey: false,
showCloseButton: true,
showCancelButton: true,
title: 'Recebendo Chamada',
html: dsHtml,
cancelButtonText:'Fechar',
confirmButtonText: 'Lançar Ticket',
width: '80%'
}).then((result) => {
if (result.value)
pop_open('man_atendimento_ticket.php?f_id_retorno=70&f_cd_ticket=');
});
}
}
And here is where i call it, with the setInterval:
$(document).ready(function(){
setInterval(function(){
retorno = buscaDadosAjax('Ramal', 'verificarLigacao', {});
if (parseInt(retorno.id_capturado) === 0)
montarModalLigacao(retorno.cd_ramal_ligacao);
}, 2000);
}
Do not do it on an interval, call it when you are ready for the next one to happen.
function montarModalLigacao(cdRamalLigacao = null) {
var dsHtml = buscaDadosAjax('Ramal', 'obtemHtmlLigacao', {
cdLigacaoRamal: cdRamalLigacao
});
console.log(dsHtml);
if (dsHtml) {
swal({
allowOutsideClick: false,
allowEnterKey: false,
showCloseButton: true,
showCancelButton: true,
title: 'Recebendo Chamada',
html: dsHtml,
cancelButtonText: 'Fechar',
confirmButtonText: 'Lançar Ticket',
width: '80%'
}).then((result) => {
if (result.value)
pop_open('man_atendimento_ticket.php?f_id_retorno=70&f_cd_ticket=');
setUpCall();
});
} else {
setUpCall();
}
}
function setUpCall() {
setTimeout(function() {
retorno = buscaDadosAjax('Ramal', 'verificarLigacao', {});
if (parseInt(retorno.id_capturado) === 0)
montarModalLigacao(retorno.cd_ramal_ligacao);
}, 2000);
}
$(document).ready(setUpCall);

I want Sweet alert to work first to change the check to true, false, what to do? [duplicate]

This question already has answers here:
What is the difference between the `=` and `==` operators and what is `===`? (Single, double, and triple equals)
(5 answers)
Closed 2 years ago.
I want Sweet alert to work first to change the check to true, false, what to do? Please help me !
$("#our-table").on('click', '#button-delete', function () {
var check = null;
Swal.fire({
title: 'Are you sure ?',
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Comfirm'
}).then((result) => {
if (result.isConfirmed) {
check == true
}
})
if (check == true) {
return true;
}
else {
return false;
}
});
Firstly if you want to return true or false according to sweetalert's confirmation, you can pass a callback function and return the checked value in this way:
function sweetChecked(callback) {
Swal.fire({
title: 'Are you sure ?',
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Comfirm'
}).then((result) => {
callback(result.isConfirmed);
})
}
$("#button-delete").on('click', function (event) {
event.preventDefault();
var URLToRedirect = event.currentTarget.getAttribute('href');
console.log(URLToRedirect);
sweetChecked(function (checked) {
if (checked) {
console.log("true");
window.location.href = URLToRedirect;
}
else {
console.log("false");
}
});
});
<script src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2#10.12.5/dist/sweetalert2.all.min.js"></script>
<a id="button-delete" href="/ManageUser/Delete/01">Delete</a>
Think the only thing you need to change is
if (result.isConfirmed) {
check = true
}
The == is actually doing a check instead of an assignment.

Javascript custom configrmation message SweetAlert.js

I want to show a custom confirmation message in my ASP.NET MVC application.
After some search, I found SweetAlert which is a very nice tool.
https://sweetalert2.github.io/
I want to define a javascript method in a js file which calls the sweetalert to show a dialog.
But the document doesn't wait for the respons of the client.
To demonstrate what I mean, I added the code below.
The code alert("Doesn't wait"); executes before sweetalert shows its message.
My objectif is to add a custom javascript file and define a simble function to call and return true or false to avoid typing all the code below in every confirmation case.
As it doesn't wait the client interaction, I don't know if it is possible.
Any idea ?
<html>
<head>
<script src="SweetAlert.js"></script>
</head>
<body>
<button onclick="customConfirm();">Confirm</button>
</body>
</html>
<script type="text/javascript">
function customConfirm(){
Swal.fire({
title: 'myTitle',
text: 'my Question',
type: 'question',
showCancelButton: true,
confirmButtonColor: 'rgb(181, 212, 83)',
cancelButtonColor: '#d33',
confirmButtonText: 'YES'
}).then((result) => {
if (result.value) {
return true;
}
else {
return false;
}
});
alert("doesn't wait.");
}
</script>
You should perform all checks in the callback.
function customConfirm(callback){
Swal.fire({
title: 'myTitle',
text: 'my Question',
type: 'question',
showCancelButton: true,
confirmButtonColor: 'rgb(181, 212, 83)',
cancelButtonColor: '#d33',
confirmButtonText: 'YES'
}).then((result) => {
// Do some stuff and call the callback
callback();
if (result.value) {
return true;
}
else {
return false;
}
});
In another file:
customConfirm(function() {
// Put some stuff you want to do
});
Or:
function callbackDoSomething() {}
customConfirm(callbackDoSomething);

How to change bootstrap toggle checkbox checked to true or false with a sweetalert confirmation event?

I am creating a page to add permissions to users. There is a toggle button which enables / disables the user. when we click on the toggle, it should pop up a sweetlalert with confirmation? " are you sure? " and cancel. I have 2 funsctions. Enable and disable
script>
$(document).on('click.bs.toggle', 'div[data-toggle^=toggle]', function(e) {
var $checkbox = $(this).find('input[type=checkbox]')
var user= $(this).attr('data-user')
if($checkbox.prop('checked') == false) {
deleteAdmin(user)
} else{
enableAdmin(user)
}
$checkbox.bootstrapToggle('toggle')
e.preventDefault()
})
My form element:
" <%=activeUser? "checked=\"checked\"":"" %>>
Functions:
function deleteAdmin(adminUserId)
{
swal({
title: 'Are you sure?',
text: "This will disable the user from Kaizen",
type: 'warning',
position: 'top-start',
showCancelButton: true,
confirmButtonColor: '#d33',
confirmButtonText: 'Yes, Disable User'
}).then((result) => {
document.location.href = '<%=request.getRequestURI()%>?<%=Constants.DELETE%>=1&limitToPerm=<%=limitToPerm%>&auId=' + adminUserId;
})
}
function enableAdmin(adminUserId)
{
swal({
title: 'Are you sure?',
text: "Are you sure you want to enable this user again?",
type: 'warning',
position: 'top-start',
showCancelButton: true,
confirmButtonText: 'Yes, Enable User'
}).then((result) => {
document.location.href = '<%=request.getRequestURI()%>?<%=Constants.UPDATE%>=1&limitToPerm=<%=limitToPerm%>&auId=' + adminUserId;
})
}
clicking on the Disable/Enable option toggles this flag before getting confirmation to perform the action. Also selecting 'cancel', the flag is still being updated. Is there a way we could intercept the event before the toggle happens.
and the toggle shouldnot happen if the cancel is clicked.

Categories

Resources