Can I have multiple Sweet Alert 2 PopUps? - javascript

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

Related

Validation for tr insert with alertbox (confirm.js) not working

I've been trying to create a dynamic table that lets the user insert rows with textboxes and confirm the data/insert it on database by clicking a confirm button. The button works just fine, it inserts the table row on click, but i need a validation where the textboxes can't be blank and i can't make it work inside the function.
i've tried creating variables for the data on the textboxes, and used a simple if to confirm they are not empty, but the confirm button keeps adding the table rows without displaying the alert
$(function tableConfirm(){
$(document).on('click','.btnConfirm', function(){
var error=0;
var campo1 = document.getElementById("campo1").value;
var campo2 = document.getElementById("campo2").value;
var campo3 = document.getElementById("campo3").value;
var campo4 = document.getElementById("campo4").value;
//Html insertion
var content='<tr><td><label class="checkContainer"><input type="checkbox"><span class="checkmark"></span></label></td><td id="texto1">'+campo1+'</td><td id="texto2">'+campo2+'</td><td id="texto3">'+campo3+'</td><td id="texto4">'+campo4+'</td><td><button class="eliminar">X<!--</Button><<i class="far fa-edit"></i></button>--></td></tr>';
$(this).parents('tr').remove();//this is to remove the textboxes before inserting the row data
$('tbody',currentView).append(content);//this appends the row data
//Validation not working
if(document.getElementById("texto1").value==""){
$.alert({
useBootstrap:false,
columnClass:'small',
title:'Error!',
content:'you must fill all the blanks!',
icon:'fas fa-exclamation-triangle',
type:'red',
typeAnimated:true,
buttons:{
tryAgain:{
text:'Ok',
btnClass: 'btn-red',
action: function(){
}
}
}
});
}
//This alertbox should only be displayed if the row has no blank spaces
else
$.alert({
useBootstrap:false,
columnClass: 'small',
title: 'Success!',
content: 'Task inserted!',
type: 'green',
icon:'fas fa-check-circle',
typeAnimated: true,
buttons: {
tryAgain: {
text: 'Ok',
btnClass: 'btn-green',
action: function(){
}
},
}
});
});
});
I expect the code to alert the user when the textboxes aren't filled, but it always inserts the task and shows the respective alert.
Thank you for your time, I appreciate any kind of help!
a TD element has no value but innerHTML so repleace the following :
wrong:
if(document.getElementById("texto1").value=="")
Correct:
if(document.getElementById("texto1").innerHTML=="")

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')}
)

sweetalert disappear Instantly

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>

Alert box error

I have to allow only alphabets to the text box. I have validated through JavaScript on text box using "on blur". The alert from the JavaScript remains open even though I try to close.
Find the demo link and the JavaScript below.
Note: Type any non-alphabet in the text box 1 and press tab or click on somewhere else from the following link.
http://demo.acclary.com/test.aspx
The JavaScript I used is, below:
function checkalphabets(textbox) {
var pattern = /^[a-zA-Z\s]+$/;
if (!pattern.test(textbox.value)) {
modal({
type: 'warning',
title: 'Warning',
text: 'Only Alphabets allowed!',
center: false,
});
setTimeout(function () { textbox.focus(); }, 1);
exit;
return false;
}
return true;
}
$('.modal-btn').click(function() {
$('#modal-window').hide();
});
You just need to add following line of code in the modal function:
callback: function(){ $("#myTextBox").focus();}
So After change, it will be like
modal({
type: 'warning',
title: 'Warning',
text: 'Only Alphabets allowed!',
center: false,
callback: function(){ $("#myTextBox").focus();}
});
That's all.
I have created fiddle using the Modal plugin that you are using in the page.
http://jsfiddle.net/7kpsv1p4/1/
change on-blur to onchange
small changes in your code
function checkalphabets(textbox) {
var pattern = /^[a-zA-Z\s]+$/;
if (!pattern.test(textbox.value)) {
textbox.focus();
modal({
type: 'warning',
title: 'Warning',
text: 'Only Alphabets allowed!',
center: false,
});
return false;
}
return true;
}
I hope this will work.
If you use onblur and focus on the textbox together the alert box will always show in the screen, because after focusing the textbox you are closing the modal alert means that you are re-belurring the textbox.
So it's better to use :
the onchange event.
Or the onKeyup event.
Note: Using the onkeyup is a better approach to refocus the textbox safely.
And try to focus on the textbox right before showing the alert, so when you close the alert the textbox will be already focused.
EDIT:
Here's a DEMO Fiddle using the onkeyup event but a simple alert, and here's the code:
function checkalphabets(textbox) {
var pattern = /^[a-zA-Z\s]+$/;
if (!pattern.test(textbox.value)) {
setTimeout(function () { textbox.focus(); }, 1);
alert('This is wrong');
exit;
return false;
}
return true;
}
It fires whenever you type a wrong character and still focuses in teh textbox.

How to keep Sencha Ext.Msg from closing on button click

So i Have a Message box I built to be able to send a message. It has 2 inputs, and an OK and Cancel buttons. I can access the contents and do the normal logic quite easily how I set it up:
Ext.Msg.show({
title: 'Send a Message: ',
cls: 'MessageBox',
html: '<div class="message-InnerContainer" >' +
'<input type="text" id="messageBoxSubject" placeholder="Subject" class="messageBox-Input"/>' +
'<textarea id="messageBoxMessage" placeholder="Message" class="messageBox-TextArea"></textarea>' +
'<div>',
closable: false,
buttons: [
{ no: 'Cancel', text:'Cancel', cls:'messageBox-CancelButton'},
{ yes: 'OK', text:'Ok', cls:'messageBox-OkButton'}
],
fn: function (btn) {
if (btn == 'ok') {
//do success logic
}
else (){
//do failure logic
}
}
});
There is only one problem: I can't seem to find a way to keep the box from auto closing when OK is pressed. Ideally I would like to run a quick check to ensure that the two inputs are not empty. I think I might just be able to override buttons by placing custom buttons in the html section, but if there is a way to halt the auto closing it would be more syntactically pleasing and readable. Does anyone know if its possible?
Oh my! You should really consider using some regular Ext text field and text area as items of the window instead of your own baked html...
Anyway, use the handler of your buttons, instead of the fn handler. You'll be able to do whatever you want in there, and close the window only if you feel like it:
buttons: [
{ text:'Cancel', cls:'messageBox-CancelButton', handler: function() {
this.hide();
}},
{ text:'Ok', cls:'messageBox-OkButton', handler: function() {
var allGood = false;
// do your stuff here
// ... and if your satisfied with the result, close the window
if (allGood) {
this.hide();
}
}}
]

Categories

Resources