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?
Related
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);
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.
I have create a sweet alert from jquery whenever an error occurs. And the sweetalert2 code for this looks as follows:
Swal.fire({
title: 'Sorry!',
text: "We couldn't find what you are looking. Let us know, so that we could add the feature in near future. ",
type: 'error',
showCancelButton: true,
confirmButtonText: 'Ok!',
confirmButtonColor: "#21b9bb",
cancelButtonText: 'Let it Go!',
reverseButtons: true
}).then((result) => {
if (result.value) {
window.open(
base_path+'/contact/request-feature',
'_blank'
);
} else if (
// Read more about handling dismissals
result.dismiss === Swal.DismissReason.cancel
) {
Swal.fire(
'Find Another Rink',
'Please, try with different search parameter.'
)
}
})
But, even after clicking either button mentioned here a backdrop still remaining there which can be viewed by inspecting the element as follows:
Because of this, the calendar becomes unclickable.
How can I get rid of this, So that I can click on the div which is covered by this div.
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();
}
});
My goal is to only allow form submission after user clicks "Ok" on a SweetAlert box.
So, he clicks on an image (form), box appears with some instructions, he reads and clicks on "Ok", and then the form is submitted.
Here is the form code:
<form id="formpag" action="https://example.com/request.html" method="post">
<input type="hidden" name="code" value="7055C88A445678A00461CFA120F4A2E7" />
<input type="image" src="https://example.com/buttons/subscriptions/120x53-subscribe.gif" name="submit" alt="Pay with Example.com - it is fast and reliable!" />
</form>
Now the jQuery/Sweet Alert part:
jQuery( document ).ready(function( $ ) {
$(function() {
$('#formpag').submit(function() {
swal({ title: "Be Advised",
text: "You need to check your email account after payment.",
imageUrl: "images/thumbs-up.jpg" });
});
});
});
Problem: as it is now, box is showing to user, but after a few seconds, the form is being submitted, even without him clicking the OK button on the SweetAlert box.
Form must only be submitted if he clicks "OK".
Any help would be much appreciated. (sorry, I know it is a silly question, but SweetAlert documentation did not help me).
You need to prevent the default handling. Update your function to following
$('#formpag').submit(function(event) {
event.preventDefault();
swal({ title: "Be Advised",
text: "You need to check your email account after payment.",
imageUrl: "images/thumbs-up.jpg" });
});
});
For reference - http://api.jquery.com/event.preventdefault/
I have done it. I found another SweetAlert code, more suitable to my need, and I could mix it to a jquery basic function.
Here is the final result:
jQuery( document ).ready(function( $ ) {
$(function() {
$('#formpag').submit(function() {
event.preventDefault();
swal({
title: "Be advised",
text: "You need to check your email account after payment.",
type: "warning",
showCancelButton: false,
confirmButtonColor: 'blue',
confirmButtonText: 'Ok, got it.',
closeOnConfirm: false,
},
function(){
$('#formpag').submit();
});
});
});
});