prevent a form from being submitted with SweetAlert - javascript

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

Related

How to use sweetalert / swal correctly?

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?

form.submit(); does not run action of form

I have a Laravel 5.8 project with using sweetalert.js.
And I have a form like this:
<form id="myForm" action="{{ route('acceptWallet') }}" method="POST">
#csrf
<input type="checkbox" id="btn-submit" name="wallet_checked" onchange="this.form.submit();">
</form>
And then, here is the route acceptWallet:
Route::post('course/accept/wallet','Wallet\WalletController#acceptWallet')->name('acceptWallet');
And at the method acceptWallet of WalletController, I have added this:
public function acceptWallet(Request $request)
{
dd($request->wallet_checked);
}
As you can see I have used onchange="this.form.submit();" to submit the form without using submit button and it works fine.
Then by using this script, I tried showing SweetAlert confirmation message box, containing Yes and No as buttons:
$(document).on('click', '#btn-submit', function(e) {
e.preventDefault();
let form = $(this).parents('form');
swal(
{
title: "Attention!",
text: "Are you sure you want to make this transaction",
type: "warning",
allowEscapeKey: false,
allowOutsideClick: false,
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes",
cancelButtonText: "No",
showLoaderOnConfirm: true,
closeOnConfirm: false
}).then((isConfirm) => {
if (isConfirm) {
form.submit();
return true;
}
return false;
});
});
As you can see I have used form.submit(); if user clicks on Yes button in order to submit the form.
But now the problem is, the form does not submitted and just refreshes the page and not showing dd($request->wallet_checked); as result.
So what's going wrong here? How can I properly submit the form after showing SweetAlert popup message?
I also tried document.forms['myForm'].submit(); instead of form.submit(); but didn't submit the form.
May be your let form = $(this).parents('form'); havent find the form correctly. So just console.log(form) and check is it available.
Also since there is a id for your form you can do something like below.
}).then((isConfirm) => {
if (isConfirm) {
document.getElementById("myForm").submit();
//Or $('#myForm').submit();
return true;
}
return false;
});
Or jest make your variable with jquery via id
let form = $('#myForm')

Unable to submit form in javascript after sweet alert has been closed

I have created an application that will feature a demo login. The Demo login will have a sweet alert pop up to let the user know that the changes they make will not be saved to the database. The problem is that the form doesn't submit after the user presses ok button that will close the sweet alert. What is the proper syntax to submit the form after the ok button has been pressed?
Below is my html:
<form method="post" id="submitForm" name="demoSubmitForm">
<div class="demo-button pt-3">
<button type="button" name="demoEmail" value="DemoEmail" class="au-btn au-btn--block au-btn--blue
m-b-20" onclick="ShowSweetAlert()">
Demo Application
</button>
</div>
</form>
Below is my script:
function ShowSweetAlert() {
Swal.fire({
icon: 'warning',
title: 'You are logging in as a Demo User!',
text: 'Changes you make to the Application will not be saved once you log out.',
onClose: document.getElementById('submitForm').submit() /*document.demoSubmitForm.submit()*/
});
}
At the moment neither do document.demoSubmitForm.submit() nor document.getElementById('submitForm').submit() work in order to submit the form.
Video of the Problem
Add this Script:
$('#submitForm').on('click', function(e) {
e.preventDefault();
var form = $(this).parents('form');
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false
}, function(isConfirm) {
if (isConfirm) form.submit();
});
});

Make jQuery click on a button when someone has confirmed (dialog box)

I have a wordpress auction site and wanted to add a confirm dialog with jquery when someone clicks on the "bid" button. I can achieve this with the default system dialog but I want a more custom dialog box with jQuery. How can I make it click the bid button once the end user has confirmed the bid?
Here is the code example:
<button type="submit" class="bid_button button alt"><?php echo wp_kses_post( apply_filters( 'bid_text', esc_html__( 'Bid', 'auctions-for-woocommerce' ), $product ) ); ?></button>
<script>
jQuery('button').confirm({
title: 'titletext',
content: 'content text"',
type: 'red',
buttons: {
ok: {
text: "OK",
btnClass: 'btn-primary',
keys: ['enter'],
action: function(){
console.log('Brukeren bekreftet "OK"');
}
},
No: function(){
text: "No",
jQuery.alert('Kansellert!');
console.log('the user clicked cancel');
}
}
});
</script>
it seems like this libary is not created for submitting forms via button, more like using it for <a> tags, source - https://github.com/craftpip/jquery-confirm/issues/229
I thought i will give you still a way to solve your problem.
now i am preventing the default behavior from the button when its not confirmed and trigger it again when its confirmed, but this time the button can submit the form.
Also added the id submitButton to your button for making it individual.
<button type="submit" id="submitButton" class="bid_button button alt"></button>
<script>
var confirmed = false;
$('#submitButton').on('click', function() {
if (!confirmed) {
event.preventDefault();
$.confirm({
title: 'titletext ',
content: 'content text"',
type: 'red',
buttons: {
ok: {
text: "OK",
btnClass: 'btn-primary',
keys: ['enter'],
action: function() {
confirmed = true;
$('#submitButton').click()
console.log('Brukeren bekreftet "OK"');
}
},
No: function() {
text: "No",
jQuery.alert('Kansellert!');
console.log('the user clicked cancel');
}
}
})
} else {
confirmed = false
}
})
</script>
hope I could help you. :)

SweetAlert Calling code after clicking "Cancel" button

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

Categories

Resources