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);
Related
Am I missing to add some script or what? I am getting error from title. How can I solve this, if you can help me, I would be grateful. I tried adding different scripts, but I amgetting the same error.
<a onclick="buyNft({{$nft->id}})">{{trans('nft.buy')}}</a>
#push('scripts')
<script>
function buyNft(nftid) {
swal({
title: "Are You Sure?",
text: "Do you want to buy this nft?",
type: 'warning',
showCancelButton: true,
showConfirmButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
}).then((result) => {
if (result) {
axios.post("/buythisnft/" + nftid).then(response => {
window.location.reload();
});
}
});
}
</script>
#endpush
Your buyNft-function needs to be declared BEFORE you echo out any element with "onclick=buyNft()":
#push('scripts')
<script>
function buyNft(nftid) {
// ...
}
</script>
#endpush
<a onclick="buyNft({{$nft->id}})">{{trans('nft.buy')}}</a>
UPDATE: This is an example using a script at the bottom of the page which creates an eventlistener for click-events:
document.addEventListener("click",e => {
if(e.target.closest(".buyNft")){
e.preventDefault();
alert("You want to buy an NFT.")
//... Replace with your own functions ...
}
})
<a class="buyNft" href="#">Buy that NFT</a>
<br /><br />
Some other link on this page
I have buttons to execute scripts in my Sheets Addon
<button class="button-68" role="button" onclick="morphf3994()">Unir columnas con el mismo encabezado</button>
<script>
function morphf3994() {
swaload()
google.script.run
.withSuccessHandler(swalsuccess)
.withFailureHandler(swalerror)
.merge_Columns();
}
</script>
And SweetAlert shows a Executing... alert while the script is making its function.
<script>
function swaload() {
Swal.fire({
titleText: "Ejecutando...",
text: 'Por favor, no toques ni cierres el documento.',
icon: 'warning',
allowOutsideClick: false,
preConfirm: Swal.showLoading(),
showLoaderOnConfirm: true,
showConfirmButton: false,
showCancelButton: true,
})
}
</script>
The Alert has just a Cancel button, but I don't know how to implement the CancelButton to stop the button function before finishing (in this case the .merge_Columns() function. Right now the Cancel Button just close the loading window.
Thanks!
Use then function of swal in your code. Reference
<script>
function swaload() {
Swal.fire({
titleText: "Ejecutando...",
text: 'Por favor, no toques ni cierres el documento.',
icon: 'warning',
allowOutsideClick: false,
preConfirm: Swal.showLoading(),
showLoaderOnConfirm: true,
showConfirmButton: false,
showCancelButton: true,
}).then((result) => {
if (result.isConfirmed) {
return true;
} else if (result.isDenied) {
return false;
}
})
}
</script>
apply condition in morphf3994 function
<script>
function morphf3994() {
if(swaload()){
google.script.run
.withSuccessHandler(swalsuccess)
.withFailureHandler(swalerror)
.merge_Columns();
}
}
</script>
Well, with this edit the function is running, but what i need is the code to STOP the .merge_Columns from executing. The function is already running when the Cancel button appears but I don't know the apps script code to stop the function.
<script>
function morphf9566() {
if(swaload()){
}
else {
google.script.run
.withSuccessHandler(swalsuccess2)
.withFailureHandler(swalerror)
.merge_Columns();
}
}
</script>
Thanks
I am new in Javascript / jQuery. I want to show some alert message using 'sweetalert' library and based on the user response the function will either return or continue.
Here is my implementation :
jQuery("#some_exchnage_request_form").on( 'submit', function(e){
// some implementation
// Now showing the alert
jQuery.getScript('https://unpkg.com/sweetalert/dist/sweetalert.min.js', function() {
swal({
title: "Do you want Continue ? ",
text: "You need to pay extra amount",
icon: "success",
buttons: true,
confirmButtonColor: '#C64EB2',
})
.then((willSubmit) => {
if (!willSubmit) {
return false;
}
});
});
// rest of the code
});
Here the expectation is if the user select 'cancel' button the function should return false, otherwise on selecting 'ok' button 'rest of the code' portion to be executed.
But here problem is the code doesn't stop for the user input and just continue. The alert box is displayed but it ignore the user selection.
I know implementation is wrong, but not sure what would be the correct way to do this.
Thanks!!
You need to use Swal.fire(); to make it work.
https://sweetalert2.github.io/
jQuery("#some_exchnage_request_form").on( 'submit', function(e){
// some implementation
// Now showing the alert
e.preventDefault();
jQuery.getScript('https://cdn.jsdelivr.net/npm/sweetalert2#11', function() {
Swal.fire({
title: 'Do you want Continue ?',
text: "You need to pay extra amount",
icon: 'success',
showCancelButton: true,
confirmButtonColor: '#C64EB2',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes'
}).then((result) => {
if (result.isConfirmed) {
Swal.fire(
'Confirmed!',
'You agreed to pay extra amount.',
'success'
)
} else {
console.log('clicked cancel');
}
})
})
// rest of the code
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="some_exchnage_request_form">
<input type="submit">
</form>
There are similar questions and looks like it is a limitation of 'sweetalert' that execution doesn't stop for user input unlike alert()/confirm() in js.
sweetalert pause execution and return value
How to return the value of SweetAlert2 input?
I have written following code, I want to call a code under "Cancel" button:
vm.saveGroup = function(){
SweetAlert.swal({
title: "Name this Device Group",
text: "Please provide a name that you want your device group to be saved under. Also, make sure that you already specified all needed filters before you save the list.",
type: "input",
showCancelButton: true,
closeOnConfirm: false,
showLoaderOnConfirm: true,
inputPlaceholder: "Device Group name"
},
function(inputValue){
if (inputValue === false) {
return false;
}
if (inputValue === "") {
/*eslint-disable */
swal.showInputError("You need to write something!");
/*eslint-enable */
return false;
}
deviceGroupsFactory.saveGroup(inputValue, vm.filterOutput)
.then(function(response){
if (response.status == 200){
SweetAlert.swal("Device Group saved!", "You should now see your device group on the list.", "success");
$state.go('main.template.devices.groups');
}
else {
SweetAlert.swal("Error!", response.statusText, "error");
console.log('xxx');
}
});
});
}
but I cannot call "cancel clicked". I was looking for in docs but cannot find the solution.
You're passing too many parameters to the swal constructor. It needs only two:
swal(options, callback)
options: Attributes to design the alert
callback: The callback function to manage the events
When you use a simple confirm, the callback receive only one parameter that indicates the user choice:
true: Confirm
false: Cancel
With inputbox you will receive the user's input string as parameter.
When you merge together inputbox and confirm, you could receive:
the input string value: When the user press Confirm
false: When user press Cancel
So, you have to use the Strict Equality Comparison in order to know if user pressed cancel or have inserted the string false in the input box.
Please see the following simple example:
swal({
title: "Are you sure?",
text: "Press CANCEL, please!",
type: "input",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "CONFIRM",
cancelButtonText: "CANCEL",
closeOnConfirm: false,
closeOnCancel: false
},
function(inputValue){
//Use the "Strict Equality Comparison" to accept the user's input "false" as string)
if (inputValue===false) {
swal("Well done!");
console.log("Do here everything you want");
} else {
swal("Oh no...","press CANCEL please!");
console.log("The user says: ", inputValue);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert-dev.min.js"></script>
I hope it helps you, bye.
you can also use the implementation of promises using .then
I give you an example, this would be executed just after pressing the button
swal( 'Error!',valido.msj,'error').then((e)=>{
if( valido.msj=="Enlace de botón No Válido" ){
document.getElementById('link_btn_barra').focus();
}
});
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();
}