sweetalert disappear Instantly - javascript

swal({
title: "xxx",
type: "warning",
showCancelButton: true,
.....
},
function(isConfirm) {
if (isConfirm) {
swal("yes, do it!");
} else {
swal("cannel!");
}
}
);
in my page a button binding a js function , the function execute this code . On the page appear the "are you sure" confirm box when I click the button. but when I click yes , the next sweetalert just flushes and disappear instantly. what's wrong?

Looks like the closing operation of the plugin uses a timer to do some cleanup, which is executed after 300ms, so the new alert also is getting cleaned up.
One hack to fix it is to use a timer like
swal({
title: "xxx",
type: "warning",
showCancelButton: true
},
function(isConfirm) {
debugger;
setTimeout(function() {
if (isConfirm) {
swal("yes, do it!");
} else {
swal("cannel!");
}
}, 400)
}
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert-dev.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.css" rel="stylesheet" />

As the problem has been solved, consider this just an another approach.
You can also use event.preventDefault() for the 2nd sweetalert. I got stuck in the same situation, except that I only had 1 sweetalert to be displayed.
From this mozilla page,
The Event interface's preventDefault() method tells the user agent
that if the event does not get explicitly handled, its default action
should not be taken as it normally would be.
On clicking the submit button, it appeared for an instance and then I was directed to another page (specified in action attribute). Since this was happening by default, using event.preventDefault() made it stay.
Thanks for sharing your doubt !

just add event.preventDefault(); before swal function it will prevent it from disappearing.

Set the closeonconfirm attribute to false i.e. closeOnConfirm: false,

Once You calling to the function which is show the sweet alert make sure calling button type should keep as button not submit.
<form method="post">
<button type="button" class="btn-wide btn btn-info" onclick="buy_harvest()">Buy</button>
<button type="submit" class="btn-wide btn-shadow btn btn-success" name="good_condition">Good condition</button>
<button type="submit" class="btn-wide btn btn-danger" name="inedible">Inedible</button> </form>
<script>
function buy_harvest(){
var { value: formValues } = Swal.fire({
title: 'How mutch want to Buy?',
showCancelButton: true,
confirmButtonText: `Buy`,
html:
'<div style="float:left;"><input type="text" id="buy_qty" style="width:150px;"><label> Quanity </label></div>' ,
focusConfirm: false,
preConfirm: () => {
var buy_qty = document.getElementById("buy_qty").value;
if(buy_qty!="" || buy_qty!=0){
//call to another function and pass value
process_buy(buy_qty);
}
}
})
}
</script>

Related

Can I have multiple Sweet Alert 2 PopUps?

My HTML/Javascript app uses a modal popup which I created using sweet Alert 2. Let's call this "Alert1".
Alert1 is using custom HTML and there is a button inside that HTML which I want to trigger another sweet alert 2 modal popup, we'll call this one "Alert2".
Alert2 has two options. "confirm" or "cancel" If the user clicks "cancel" I want to return to Alert1.
Here is the catch: The custom HTML for Alert1 is editable therefore, I can't just re-invoke the code that originally launched the alert, because this would show the old HTML.
This is what I have tried:
function clickButton(){ //This function will be attached to the button in Alert1
var currentSwal = document.getElementById('swal2-content').innerHTML;
swal({
title: "Confirm 'Remove Script Page'",
text:
"Are you sure you want to remove this page from the script?",
type: "warning",
showConfirmButton: true,
showCancelButton: true
}).then(function(dismiss) {
if (dismiss.dismiss == "cancel" || dismiss.dismiss == 'overlay') {
swal.close;
swal({
html: currentSwal,
showConfirmButton: false,
customClass: 'swal-extra-wide',
showCloseButton: true
});
} //end if
else {
//go ahead and delete the script page
} //end else
});
}//end function
My above solution does not work. It is a bit hard to explain, but basically, the HTML code gets broken and things just don't work properly.
TLDR/My question: Is there a way to have multiple SweetAlert2 alerts? (i.e. launch alert2 from alert1 and then close alert2, returning the view to alert1?
Yes you can ,
var modals = [];
modals.push({title: 'title Of Modal1', text: 'text1' });
modals.push({title: 'title Of Modal2', text: 'text2' });
swal.queue(modals);
References
Question 38085851 Answer 1
make a for loop for 3 and use toast not sweet alert and it will be works

Cannot Close Sweet Alert 2 Modal On Custom HTML Button Click

I am having a very hard time for debugging this. I am using custom HTML parameter from SweetAlert2. What I want to achieve is that whenever I click "Back" Button, I want to close the modal. I did read the documentation. we can usee swal.close() or swal.closeModal(). But when I doing it, I can't close the modal upon a back button. Below are the codes.
//declare custom html
const cancelBtn = `<button class="cancelSwalBtn" id="standardCancelBtn" >Back</button>`;
const removeAddOnBtn = `<button class="removeAddonSwalBtn" id="standardRemoveAddonBtn">Remove Add-ons</button>`;
const proceed = `<button type="button" role="button" tabindex="0" class="proceedSwalBtn" id="standardProceedBtn">Proceed</button>`;
const html = `<p>Your voucher does not cover the cost additional of addons. </p><div class="btn-holder">${cancelBtn}${removeAddOnBtn}${proceed}</div>`;
//custom swal
swal({
type: 'info',
title: 'Info',
html: `${html}`,
width :700,
showCancelButton: false,
showConfirmButton:false,
onOpen: (swal) => {
//close btn
$(swal).find('#standardCancelBtn').click(function (e) {
console.log('in');
swal.close();
//swal.closeModal();
})
}
}).then((result) =>{
console.log(result);
});
swal.close() or swal.closeModal() should work.
Ref.: SweetAlter Methods
onclick="swal.close(); return false;"
Simply add: onclick="swal.closeModal(); return false;" inside your html button like this:
const cancelBtn = `<button class="cancelSwalBtn" id="standardCancelBtn" onclick="swal.closeModal(); return false;">Back</button>`;

MVC Javascript Button Value Incorrect

I am using MVC - in one of my views I have a button that I want to toggle the value on click. Here's the button code in the view:
<div class="col-md-10">
<input type="button" value="Yes" class="btn btn-default" id="CanOrder" />
</div>
And this is my javascript for its click event:
<script>
$('#CanOrder').click(function () {
if ($(this).val('Yes')) {
alert("button says Yes");
$(this).val('No');
}
else {
alert("button says No");
$(this).val('Yes');
}
});
</script>
At the very beginning, this works...the button shows "Yes", and when I click on it I get the alert "button says Yes" and then it changes to "No".
But after that, what happens is whenever I click on it, it immediately changes the text on the button to "Yes", then I get the alert saying "button says Yes", and it changes back to "No".
If I try running the page without the alerts, I don't even see it ever change back to "Yes" - it acts like clicking it the first time works and then it only ever says "No" whenever I click on it after that.
What am I doing wrong?
Thank you!
In order to check the value of CanOrder you need to correct your if statement:
<script>
$('#CanOrder').click(function () {
if ($(this).val() === "Yes") {
alert("button says Yes");
$(this).val('No');
}
else {
alert("button says No");
$(this).val('Yes');
}
});
</script>
You can learn more about the val method here.

SweetAlert: block event like JavaScript Alert()

I have a function that asks users for confirmation when selecting a value from a Select dropdown. When using the regular JavaScript confirm(), the change event does not get the newly selected value without clicking on confirm. This can be seen in this Fiddle.
When a value is selected, and the user clicks cancel, the same value is shown in an alert dialog. When the user clicks confirm, the newly selected value is displayed.
However, I'd like to use SweetAlert. When changing the value with SweetAlert, the change happens without even selecting confirm or cancel. As demonstrated in this Fiddle. When a value is selected, an alert dialog is displayed right after selection, unlike with the pure JS Confirm() which blocks the event somehow.
I'd like to achieve the same effect as the JS confirm(), where the change event is not triggered while the user has not clicked confirm or cancel, when using SweetAlert.
Aside from both Fiddles which demonstrate the problem, here's the code I'm using:
Some simple HTML select:
<select id="dropdownId">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
The JavaScript confirm() version (which does what it needs to do):
var prev_val;
$('#dropdownId').focus(function () {
prev_val = $(this).val();
}).change(function (e) {
var select = this;
$(this).blur();
var success = confirm('Are you sure you want to change the Dropdown?');
if (success) {
// Other changed code would be here...
} else {
$(this).val(prev_val);
return false;
}
});
$('#dropdownId').change(function (e) {
alert($(this).val());
});
And the SweetAlert version, where the change event should wait on the response of the SweetAlert dialog.
var prev_val;
$('#dropdownId').focus(function () {
prev_val = $(this).val();
}).change(function (e) {
var select = this;
$(this).blur();
return swal({
title: "Are you sure?",
text: "Change dropdown select?",
type: "warning",
showCancelButton: true,
confirmButtonText: "Yes!",
cancelButtonText: "No!",
closeOnConfirm: true,
closeOnCancel: true
},
function (isConfirm) {
if (isConfirm) {
return true;
} else {
$(select).val(prev_val);
return false;
}
});
});
$('#dropdownId').change(function (e) {
alert($(this).val());
});
Edit:
Moving the logic to the confirm handler of the dialog does not solve this issue. I'm using a framework (Apache Tapestry) which listens for a change event on the select. When using the solution as RRR stated, in this fiddle, the change event still happens. Which still causes it to fire an event to my backend, unlike with the JS confirm() which does not change the value until confirm was clicked.
Edit 2:
My problem doesn't really seem to be that clear. Here are the steps I undertake to try and show what the root of the problem is:
When using the JS confirm from this fiddle. The following happens:
I click on a value
It asks for confirmation
On confirm, it logs the new value. On cancel, it logs the original value.
When using the SweetAlert dialog, using this fiddle. The following happens:
I click on a value
It logs the newly selected value, before confirming/cancelling
On confirm/cancel I can execute logic.
When using the SweetAlert dialog, as edited by RRR in this fiddle. The following happens:
I click on a value
It logs the newly selected value, before confirming/cancelling
On confirm/cancel, it shows an alert
Both my and RRR's SweetAlert example have the same issue. Namely, step 2. Not the fact that it logs, but the fact that the value actually changes. Unlike in the first pure JS example, where the value does NOT change unless confirm is clicked.
Ok. Here is the issue.
You call 2 different actions at onchange event:
1- The big function...
2- A test alert.
Both occur at the same time. <-- Here lies the confusion!
This is why it appeared to you that swal doesn't "wait" to get an answer from the user.
Try this... And look at your console.log messages:
var prev_val;
$('#dropdownId').focus(function () {
prev_val = $(this).val();
console.log("On focus event value : "+prev_val); // ADDED
}).change(function (e) {
var select = this;
console.log("At the BEGINNING of the change event : "+$(select).val()); // ADDED
$(this).blur();
swal({ // REMOVED return in front of it
title: "Are you sure?",
text: "Change dropdown select?",
type: "warning",
showCancelButton: true,
confirmButtonText: "Yes!",
cancelButtonText: "No!",
closeOnConfirm: true, // These are default.. useless to specify
closeOnCancel: true // These are default.. useless to specify
},
function (isConfirm) {
if (isConfirm) {
//return true; // no need to return anything - commented out
console.log("swal YES");
console.log("At the END of the change event : "+$(select).val());
} else {
$(select).val(prev_val);
//return false; // no need to return anything - commented out
console.log("swal NO");
console.log("At the END of the change event : "+$(select).val());
}
// Here is a callback final test alert!
alert("Callback alert: "+$(select).val());
});
});
/*$('#dropdownId').change(function (e) { // This was a bad idea ! ;)
alert($(this).val());
});*/
In my case sweet alert 2 was blocking my binded event handlers:
Swal.fire( // Not works - Nothing will happen onclick
{html: `<button id="btn1" onclick="alert('clicked')">Delete</button>`,
)
So i binded the event handlers in javascript instead, on modal open:
Swal.fire(
{html: `<button id="btn1">Delete</button>`,
onOpen: () => {document.querySelector('#btn1').onclick = () => {alert('clicked')}
)

How to detect button value change in JQuery?

I've a sign up form which has submit button with value "GET INSTANT ACCESS!" :
<input type="submit" class="wf-button" name="submit" value="GET INSTANT ACCESS!">
After submit, the value gets change to 'Thank You!':
<input type="button" class="wf-button" value="Thank You!">
I need to detect the button value. If it becomes "Thanks You!" then I have to show a popup. And this value gets change by some Ajax (GetResponse form). There is no page refresh.
I've tried below code but it is only working in FireFox & not working in Chrome.
<script>
$(function() {
$(".modalbox").fancybox();
});
$(function() {
$('.wf-button').bind("DOMSubtreeModified",function(){
//if btn valu is 'Thank You! trigger popup'
$(".modalbox").trigger('click');
});
});
</script>
Live URL: http://www.idynbiz.com/web/html/gold_ira_vf/? (just to show how the button changes its value)
Can some one help how can I detect the button value and show my popup? The button change its value in real time (Ajax). There is not page refresh.
Is there any JQuery approach with bind() Or on() function to detect the value?
$(function() {
$('.btn1').on('change', function() {
alert('Do stuff...');
});
$('.lnk1').on('click', function() {
$('.btn1').val('Thank you!');
$('.btn1').trigger('change');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="submit" class="btn1" value="SUBSCRIBE" />
Change button value
OK ,
when button is clicked and form is submitted for saving. just write these code
$(document).ready(function ()
{
$('.wf-button').click(function ()
{
var valueofbutton = $(this).attr('value');
if(valueofbutton == 'Thank You!')
{
window.open(); //// whatever you want to open in popup
}
});
});
i m sure that this will work
You can use the following function in javascript which gets called after any > kind of postback, i.e. synchronous or asynchronous.
function pageLoad()
{
if($(".wf-button").val()=="Thank You!")
{
// show your popup
}
}
Hope it works....

Categories

Resources