How to set Yes & No button actions on hyperlink in SweetAlert - javascript

I have a hyperlink like this:
<a href="{{ route('courseRegistration', $item->cor_id) }}" class="btn btn-info" id="custombtn">
Register
</a>
Then I added this to show a Sweetalert message with Yes and No buttons:
$(document).on('click', '#custombtn', function(e) {
e.preventDefault();
let form = $(this).parents('form');
swal(
{
title: "Alert!",
text: "You have an active Wallet, do you wish to pay the price with the active Wallet?",
type: "warning",
allowEscapeKey: false,
allowOutsideClick: false,
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes",
cancelButtonText: "No",
showLoaderOnConfirm: true,
closeOnConfirm: false
}).then((isConfirm) => {
if (isConfirm.value === true) {
// go to the href route
}
return false;
});
});
As you can see I want to say: if user clicked on the Yes button, goto href route and if not, stays on the page (return false).
So the question is, how can I redirect user to href="{{ route('courseRegistration', $item->cor_id) }}", if he clicks on Yes button?

you can use window.location.href = "YOURLINKHERE" to redirect to another page after checking if isConfirm.value is set (you dont have to check for true, since the cancel Button doesn't return isConfirm.value)

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

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.

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