SweetAlert prompt with two input fields - javascript

Currently working on a personal project. I want the user to click a button and a SweetAlert prompt would be presented for the user to verify their credential. However, the code I see on the SweetAlert website only allows one input field. Here is the code I have:
swal({
title: "Authenicating for continuation",
text: "Test",
type: "input",
showCancelButton: true,
closeOnConfirm: false,
animation: "slide-from-top",
inputPlaceholder: "Write something"
}, function(inputValue) {
if (inputValue === false) return false;
if (inputValue === "") {
swal.showInputError("You need to write something!");
return false
}
// swal("Nice!", "You wrote: " + inputValue, "success");
});
So, is there a way I can get two input fields? One input field for the password and the other input field for text.

Now SweetAlert2 is available:
https://sweetalert2.github.io
As per their info on bottom:
Multiple inputs aren't supported, you can achieve them by using html
and preConfirm parameters. Inside the preConfirm() function you can
pass the custom result to the resolve() function as a parameter:
swal({
title: 'Multiple inputs',
html:
'<input id="swal-input1" class="swal2-input">' +
'<input id="swal-input2" class="swal2-input">',
preConfirm: function () {
return new Promise(function (resolve) {
resolve([
$('#swal-input1').val(),
$('#swal-input2').val()
])
})
},
onOpen: function () {
$('#swal-input1').focus()
}
}).then(function (result) {
swal(JSON.stringify(result))
}).catch(swal.noop)

Multiple inputs aren't supported, you can achieve them by using HTML and preConfirm parameters.
Inside the preConfirm() function you can return (or, if async, resolve with) the custom result:
function sweetAlert(){
(async () => {
const { value: formValues } = await Swal.fire({
title: 'Multiple inputs',
html:
'<input id="swal-input1" class="swal2-input">' +
'<input id="swal-input2" class="swal2-input">',
focusConfirm: false,
preConfirm: () => {
return [
document.getElementById('swal-input1').value,
document.getElementById('swal-input2').value
]
}
})
if (formValues) {
Swal.fire(JSON.stringify(formValues))
}
})()
}
body {
font-family: "Open Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", Helvetica, Arial, sans-serif;
}
<script src="https://cdn.jsdelivr.net/npm/sweetalert2#9.3.4/dist/sweetalert2.all.min.js"></script>
<button onclick="sweetAlert()">Try me!</button>
Source: INPUT TYPES

You can have inputs in the default SweetAlert type, as long as you set the html property to true. The issue is that unless the type is set to "input", SweetAlert adds a display: none to input fields.
It's a bit of a workaround, but you can change this in the js file from
<input type=\"text\" tabIndex=\"3\" />\n
to
<input id=\"swalInput\" type=\"text\" tabIndex=\"3\" />\n
And change the css file from
.sweet-alert input {
to
.sweet-alert #swalInput {
Then you can simply add your html to the text parameter when calling, like so:
swal({
title: "Log In to Continue",
html: true,
text: "Username: <input type='text'><br>Password: <input type='password'>"
});
This method simply specifies that the only input to be styled that way is the one generated by SweetAlert, so that any inputs you add to your text won't be affected by that styling.

Using the example posted by Tikky in their answer above and based on the question asked for validation on that answer. You could possibly try the following to implement validation on this method:
swal({
title: 'Multiple inputs',
html:
'<input id="swal-input1" class="swal2-input">' +
'<input id="swal-input2" class="swal2-input">',
preConfirm: function () {
return new Promise(function (resolve) {
// Validate input
if ($('#swal-input1').val() == '' || $('#swal-input2').val() == '') {
swal.showValidationMessage("Enter a value in both fields"); // Show error when validation fails.
swal.enableConfirmButton(); // Enable the confirm button again.
} else {
swal.resetValidationMessage(); // Reset the validation message.
resolve([
$('#swal-input1').val(),
$('#swal-input2').val()
]);
}
})
},
onOpen: function () {
$('#swal-input1').focus()
}
}).then(function (result) {
// If validation fails, the value is undefined. Break out here.
if (typeof(result.value) == 'undefined') {
return false;
}
swal(JSON.stringify(result))
}).catch(swal.noop)

As far as I know you can't do this off-the-shelf. You can either fork and implement, or just use a HTML element as a modal (e.g. as in Bootstrap's modals).

$(document).ready(function(){
$("a").click(function(){
swal({
title: "Teste",
text: "Test:",
type: "input",
showCancelButton: true,
closeOnConfirm: false,
animation: "slide-from-top",
inputPlaceholder: "User"
},
function(inputValue){
if (inputValue === false) return false;
if (inputValue === "") {
swal.showInputError("Error");
return false;
}
swal({
title: "Teste",
text: "E-mail:",
type: "input",
showCancelButton: true,
closeOnConfirm: false,
animation: "slide-from-top",
inputPlaceholder: "Digite seu e-mail"
},
function(inputValue){
if (inputValue === false) return false;
if (inputValue === "") {
swal.showInputError("E-mail error");
return false;
}
swal("Nice!", "You wrote: " + inputValue, "success");
});
});
});
});

Multiple inputs aren't supported, you can achieve them by using html and preConfirm parameters.
Notice that in preConfirm function you can pass the custom result to resolve():
You can do this using such manner:
swal({
title: 'Multiple inputs',
html:
'<h2>Login details for waybill generation</h2>'+
'<input id="swal-input1" class="swal2-input" autofocus placeholder="User ID">' +
'<input id="swal-input2" class="swal2-input" placeholder="Password">',
preConfirm: function() {
return new Promise(function(resolve) {
if (true) {
resolve([
document.getElementById('swal-input1').value,
document.getElementById('swal-input2').value
]);
}
});
}
}).then(function(result) {
swal(JSON.stringify(result));
})
}
The link here: https://limonte.github.io/sweetalert2/

It's very simple through the preConfirm method and using ok button as submission button in sweetalert2
swal.fire({
showCancelButton:true,
html:`input1:<input id="input1" type="text">
input2: <input id="input2" type="text">
input3: <input id="input3" type="text">`,
preConfirm:function(){
in1= $('#input1').val();
in2= $('#input2').val();
in3 = $('#input3').val();
console.log(in1,in2,in3) // use user input value freely
}
})

Here is an example using sweetalert#^2.1.0, showing one way to have multiple input fields. The example uses jQuery, but jQuery is not required for this technique to work.
// ==============================================================
//swal does not block, and the last swal wins
//so these swals are closed by later calls to swal, before you can see them
// ==============================================================
swal("aaa");
swal("bbb");
// ==============================================================
//for multiple inputs, use content: anHtmlElement
// ==============================================================
const div = document.createElement("div");
console.log(div);
$(div).html("first<input id='111' value='one'></input></br>second<input id='222' value='two'></input></br>third<input id='333' value='three'></input>");
swal({
title: "Three Inputs",
content: div,
// ==============================================================
//true means show cancel button, with default values
// ==============================================================
buttons: [true, "Do It"]
}).then(value => {
if (value) {
const outputString = `
value is true for confirm (i.e. OK); false for cancel
value: ${value}
` + $("#111").val() + " " + $("#222").val() + " " + $("#333").val();
// ==============================================================
// there are no open swals at this point, so another call to swal is OK here
// ==============================================================
swal(outputString);
} else {
swal("You cancelled");
}
});
alert("swal is not blocking: " + $("#111").val() + " " + $("#222").val() + " " + $("#333").val());

Try this way
swal({
text: 'First Input',
content: "input",
button: {
text: "Add New",
closeModal: false,
},
})
.then(name => {
swal({
text: 'Second Input',
content: "input",
button: {
text: "Add New",
closeModal: false,
},
}).then(id => {
//save code here.
})
}).catch(err => {
swal("Error");
});

On SweetAlert 2.x you can use this vanilla Javascript for getting / setting one input. Yo can chain more elements to content so you can have multiple inputs:
var slider = document.createElement("input");
slider.type = "number";
slider.value = 5;
slider.step=1;
slider.min = 5;
slider.max = 50;
this.swal({
title: 'Request time to XXX',
text: 'Select values',
content: slider,
buttons: {
cancel: "Run away!",
catch: {
text: "Throw Pokéball",
value: slider.value,
},
defeat: true,
}
}).then((value) => {
console.log(slider.value); // Here you receive the input data value
//swal(`You typed: ${value}`);
});

check this out
https://sweetalert2.github.io/
"AJAX request example" + "Chaining modals (queue) example" has inputs and you can work with them

Email and Password login double input boxes in Asp.Net Core MVC with ajax to clear application session and relogin to reassign session. The "sweetModal" function should be called in javascript for application 5mins idle timer trigger for the sweetalert modal popup. Adjust to suit your need. Please note, this applies to SweeetAlert 2.0 of https://sweetalert.js.org/ and jQuery v3.5.1
sweetModal = () => {
swal({
icon: '../../../images/yourlogo.png',
title: 'Relogin',
content: {
element: "input",
attributes: {
placeholder: "Enter username",
},
},
buttons: {
confirm: {
text: "Submit",
value: true,
visible: true,
className: "",
closeModal: false
},
cancel: {
text: "Cancel",
value: null,
visible: true,
className: "",
closeModal: true
},
},
closeOnClickOutside: false,
closeOnEsc: false,
})
.then((user) => {
if (user) {
swal({
icon: '../../../images/yourlogo.png',
title: 'Relogin',
content: {
element: "input",
attributes: {
placeholder: "Enter password",
type: "password",
},
},
buttons: {
confirm: {
text: "Submit",
value: true,
visible: true,
className: "",
closeModal: false
},
cancel: {
text: "Cancel",
value: null,
visible: true,
className: "",
closeModal: true
},
},
closeOnClickOutside: false,
closeOnEsc: false,
})
.then((pwd) => {
if (pwd) {
$.post("/account/refreshsession", { user: user, pwd: pwd }, () => swal(`Successful!`));
//swal(`The returned value is: ${user} ${pwd}`);
}
});
}
});
}

The way I add 2 or more input fields is; I set html to true and use text to write you inputs, just make sure to add the class "show" (display: block) to your inputs. Swal will hide your inputs. Example:
swal({
title: "Test",
html: true,
text: ` <input class="show" tabindex="1" placeholder="">
<input class="show" tabindex="1" placeholder="">
`
}

This is working in my case
swal({
title: "Update Score",
// type: "input",
// inputPlaceholder: "Home",
showCancelButton: true,
// cancelButtonText: "Cancel",
// closeOnConfirm: false,
// closeOnCancel: false
html: true,
text: '<input id="input1" type="text" placeholder="Home" style="display:block !important;"><br><input id="input2" type="text" placeholder="Away" style="display:block !important;">',
},
function () {
in1 = $('#input1').val();
in2 = $('#input2').val();
alert(in1 + " = " + in2)
});

Yes you can!!!
swal({
title: "An input!",
text: "Write something interesting:",
type: "input",
showCancelButton: true,
closeOnConfirm: false,
animation: "slide-from-top",
inputPlaceholder: "Write something"
},
function(inputValue){
if (inputValue === false) return false;
if (inputValue === "") {
swal.showInputError("You need to write something!");
return false
}
swal("Nice!", "You wrote: " + inputValue, "success");
});

Related

How to write pre filled input in bootbox

I want bootbox to fill var name into bootbox input on click update button, but it is not doing it. I have also highlighted the same in the code below
$(document).on("click", ".update", function () {
var button = $(event.relatedTarget); /*Button that triggered the modal*/
var name = button.data('name');
modal.find('.bootbox-input-text').val(name);
$('.bootbox-form').find('input').val(name); /* Not Working */
bootbox.prompt({
title: 'Enter Description',
placeholder: 'my placeholder',
buttons: {
confirm: {
label: 'Submit'
}
},
callback: function (value) {
value && alert('You have entered: ' + value);
}
});
});
As noted in the documentation, you can provide the initial value for a prompt using the value option:
$(document).on('click', '.update', function (e) {
let button = $(this); /*Button that triggered the modal*/
let name = button.data('name');
bootbox.prompt({
title: 'Enter Description',
placeholder: 'my placeholder',
value: name, /* this is the option you would use */
buttons: {
confirm: {
label: 'Submit'
}
},
callback: function (value) {
value && alert('You have entered: ' + value);
}
});
});

linking a button to another page in SweetAlert

am i using sweet alert and i have 2 buttons; one is cancel button and the another one is continue button. i want to link the 'continue' button to another page that is 'trial.php'. how can i proceed with this? below is code i've tried:
if(m <= 2){
swal({
title:"dataset file is: "+ ""+size2 +"Mb",
text: "a cluster of 1 node will be required for processing",
buttons: {
cancel: true,
confirm: "continue"
}
})
Use .then() to watch the value of the pressed button and if the value is "continue", use window.location.href to redirect user to another page:
swal({
title: "dataset file is: " + "" + size2 + "Mb",
text: "a cluster of 1 node will be required for processing",
buttons: {
cancel: true,
confirm: "continue"
}
}).then((value) => {
if (value === "continue") {
window.location.href = "trial.php";
}
});
swal({ title: "test", text: "testing", buttons: { cancel: true, confirm: "continue" } }).then((value) => { if (value) { window.location.href = "trial.php"; } });

How to change checkbox property checked to true or false within sweet alert

I'm looking to use sweet alert to confirm when an user click on a checkbox, it displays a message asking for confirmation. but i want to the checkbox go back to the unchecked status (prop("checked", false)) if the user click to cancel the operation.
I tried to create a function inside the swal, and after the if/else function, but I couldn't discover how to make swal return something neither make it execute a function when the button cancel is clicked. I'm facing problems to find the checkbox inside the swal object too.
HTML
<input class="accomplish" id="task-checkbox1" value="1" type="checkbox" data-toggle="toggle" data-onstyle="success" data-offstyle="danger" data-on="Acomplished" data-off="Not Acomplished">
<script>
$("input.accomplish").change(function(){
if ($(this).is(":checked")){
var output = true;
swal({
title: 'Are you Sure?',
icon: 'warning',
buttons:{
cancel: {
visible: true,
text : 'Cancel',
className: 'btn btn-danger'
},
confirm: {
text : 'Accomplish Task',
className : 'btn btn-success'
}
}
}).then((willDelete) => {
if (willDelete) {
swal("Task Accomplished Successfully", {
icon: "success",
timer: 1500,
buttons : {
confirm : {
text: "Finish",
className: 'btn btn-primary'
}
}
});
} else {
output = false;
swal("Ok, we finish this task later", {
icon: "info",
timer: 1500,
buttons : {
confirm : {
text: "Dismiss",
className: 'btn btn-primary'
}
}
});
}
});
} else {
swal({
title: 'Trying to undone this task?',
icon: 'warning',
buttons:{
cancel: {
visible: true,
text : 'calcel',
className: 'btn btn-danger'
},
confirm: {
text : 'Undone Task',
className : 'btn btn-success '
}
}
}).then((willDelete) => {
if (willDelete) {
swal("Task is pending again", {
icon: "success",
//timer: 1500,
buttons : {
confirm : {
text: "Finish",
className: 'btn btn-primary'
}
}
});
} else {
swal("This task keeps accomplished", {
icon: "info",
//timer: 1500,
buttons : {
confirm : {
text: "Dismiss",
className: 'btn btn-primary'
}
}
});
}
});
}
});
</script>
When I try to create a function like
$("#task-checkbox1").prop("checked", false);
inside the swal or inside the if/else it always execute before the button being pressed.
you could try to reference this
$(document).ready(() => {
$("input.accomplish").change(function(){
const that = this // here a is change
and after the cancel button click you unchecked the checkbox
else {
that.checked= false;// here is a change
output = false;
swal("Ok, we finish this task later", {
icon: "info",
timer: 1500,
buttons : {
confirm : {
text: "Dismiss",
className: 'btn btn-primary'
}
}
});
}
You're using swal2 plugin, not original swal
HTML was introduced here before it was in swal and there's a difference in usage. Instead of
text: "",
html: true
you shoud use
html: "",

Highlighting default text input in sweetAlert

I have a SweetAlert2 that allows text input, and I give it a default value. I'd like this default value to be highlighted when the alert pops up, so that the user can immediately overwrite it if needed. Here's an example:
And here is the function that I call with the sweetAlert options:
window.sweetPrompt = function (title, message, callback, input, keepopen, allowOutsideClick, allowEscapeKey) {
sweetAlert({
title: title,
text: message,
input: 'text',
confirmButtonColor: "#428bca",
preConfirm: function(text) {
return new Promise(function(resolve) {
if (!keepopen) {
resolve();
} else {
callback(text);
}
});
},
inputValidator: function(text) {
return new Promise(function (resolve, reject) {
if (text) {
resolve();
} else {
reject('Cannot be empty!');
}
});
},
inputValue: input,
showCancelButton: true,
reverseButtons: true,
allowOutsideClick: allowOutsideClick,
allowEscapeKey: allowEscapeKey
}).then(callback, function(dismiss){});
};
How would I go about doing this (if it's possible) ? I thought about using jQuery but I'm not sure how to get the reference to the sweetAlert dialogue.
Any suggestions would be appreciated.
Here you go:
Swal.fire({
input: 'text',
inputValue: 'input value',
didOpen: () => {
Swal.getInput().select()
}
})
<script src="https://cdn.jsdelivr.net/npm/sweetalert2#11"></script>
PS. Please note that SweetAlert2 and SweetAlert are two different projects with slight differences in API.
SweetAlert2 documentation: https://sweetalert2.github.io/

Uncaught (in promise) cancel using SweetAlert2

how do I properly escape the cancel button without throwing an error when using promises? My code throws an alert confirmation with a required checkbox. the code executes as it should to the user, but it throws an error in the console window:
Uncaught (in promise) cancel
//validation logic all passes...Now proceed to...
else
{
//determine and parse Discounts
var myLookup = document.getElementsByName("myLookup")[0].value;
$.post( "findthem.php", {myLookup: myLookup })
.done(function(json_data){
var theResponse1 = $.parseJSON(json_data);
myDiscountRate = theResponse1['ourDiscountFound'];
}).then( function(callback){
priceRate = priceRate * (1 - (.01 * myDiscountRate));
newRate = priceRate.toFixed(2);
}
swal({
title: "Confirm",
input: 'checkbox',
inputValue: 0,
type: "warning",
inputPlaceholder: 'I agree to Your new Rate is :'+newRate,
showCancelButton: true,
confirmButtonText: 'Confirm',
showLoaderOnConfirm: true,
preConfirm: function(result) {
return new Promise(function(resolve, reject) {
if (result) {
$.post("my.php", {
Data: data
})
.done(
function(json_data) {
var data_array = $.parseJSON(json_data);
var moreDetails = '';
var resulting = 'error';
var details = "Transaction Declined"
if (data_array["trxApproved"] == true) {
resulting = 'success';
details = "Confirmed"
moreDetails = "<br>Approved<b>" + data_array["approved"] + "</b>" +
"<br>Details Code: <b>" + data_array["detailsCode"] + "</b>";
}
swal({
type: resulting,
title: details,
html: "<h1>Details: </h1>" + data_array["messagetext"] + moreDetails
});
}
);
resolve();
} else {
reject('You must agree to our Terms & Conditions ');
}
});
},
allowOutsideClick: false
}).then(function(json_data) {
})
});
Update (Jan 2017): This issue has been fixed in v7: v7 upgrade guide ↗
You need to add a rejection handler to the Promise. Alternatively, you can use .catch(swal.noop) as a quick way to simply suppress the errors:
swal('...')
.catch(swal.noop);
PS. the package you're using is called SweetAlert2, not SweetAlert. In future questions please mention it so you can get more relevant answers.
SweetAlert2 rejects the result promise when the cancel button is pressed. You can handle that:
swal({
…
}).then(function(json_data) {
…
}, function(dismiss) {
if (dismiss === 'cancel') { // you might also handle 'close' or 'timer' if you used those
// ignore
} else {
throw dismiss;
}
})
If you don't need to do anything with the json_data, you might also use the catch method.
new Promise(function(resolve, reject) { is not necessary. $.post() returns a jQuery promise object.
Possible solution substitutes Promise.reject() for new Promise() constructor; removed .then() that was placed as an option to first swal() call; pattern appears to expect a Promise to be returned from preConfirm, though not certain what value is expected to be returned from .done() other than json_data.
swal({
title: "Confirm",
input: 'checkbox',
inputValue: 0,
type: "warning",
inputPlaceholder: 'I agree to ',
showCancelButton: true,
confirmButtonText: 'Confirm',
showLoaderOnConfirm: true,
preConfirm: function(result) {
if (result) {
return $.post("my.php", {
Data: data
})
.done(
function(json_data) {
var data_array = $.parseJSON(json_data);
var moreDetails = '';
var resulting = 'error';
var details = "Transaction Declined"
if (data_array["trxApproved"] == true) {
resulting = 'success';
details = "Confirmed"
moreDetails = "<br>Approved<b>" + data_array["approved"] + "</b>" +
"<br>Details Code: <b>" + data_array["detailsCode"] + "</b>";
}
swal({
type: resulting,
title: details,
html: "<h1>Details: </h1>" + data_array["messagetext"] + moreDetails
});
}
);
} else {
return Promise.reject('You must agree to our Terms & Conditions ');
}
},
allowOutsideClick: false
});
you will need to catch the action for cancel
swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then(function(json_data) {
//delete item
}, function(dismiss) {
if (dismiss === 'cancel' || dismiss === 'close') {
// ignore
}
})
Adding catch(swal.noop); at the end swal function will solve this problem
For example:
swal({
}).then(function() {
}).catch(swal.noop);

Categories

Resources