16

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.

Sebastian Simon
  • 14,320
  • 6
  • 42
  • 61
ballerz
  • 367
  • 2
  • 4
  • 14

14 Answers14

28

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)
Tikky
  • 976
  • 1
  • 12
  • 26
  • And what If I need validation too in those cases? – Pardeep Jain Jul 23 '19 at 09:42
  • @PardeepJain, please see my answer where I edited Tikky's example to include validation https://stackoverflow.com/a/62244976/3948544. Original credit for the answer remains with Tikky. – Christopher Smit Jun 07 '20 at 12:00
  • @Tikky it was informative. I do have a question in regards combination of the label and input options. Can you please help here https://stackoverflow.com/questions/65566877/align-label-and-select-dropdown-in-the-same-row-in-the-sweetalert-2 – app Jan 04 '21 at 17:31
8

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.

DaftDeath
  • 99
  • 1
  • 5
6

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).

Michael Bar-Sinai
  • 2,677
  • 18
  • 24
  • 3
    Now with sweetalert2 you can, using {content: anHtmlElement}. See my post below. [SweetAlert 2 Docs](https://sweetalert.js.org/docs/#content) – Stan Mar 30 '18 at 13:35
  • Thanks @Stan ! SweetAlert 1.x and 2.x have diferent spec. Here there's a mix of SweetAlert 1.x and 2.x. html is not working for 2.x so you have to use contents – gtamborero May 31 '20 at 22:37
4

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

Mr.Senhaji
  • 133
  • 11
3
$(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"); 
            });
        });                 
    });
});
Hassaan
  • 922
  • 8
  • 16
2

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/
Abhradip
  • 283
  • 2
  • 24
2

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 
                     }
         })
Ahmed Maher
  • 681
  • 8
  • 16
  • it was informative. I do have a question in regards combination of the label and input options. Can you please help here https://stackoverflow.com/questions/65566877/align-label-and-select-dropdown-in-the-same-row-in-the-sweetalert-2 – app Jan 04 '21 at 17:31
2

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)
Christopher Smit
  • 712
  • 7
  • 19
  • it was informative. I do have a question in regards combination of the label and input options. Can you please help here https://stackoverflow.com/questions/65566877/align-label-and-select-dropdown-in-the-same-row-in-the-sweetalert-2 – app Jan 04 '21 at 17:31
1

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());
Stan
  • 148
  • 1
  • 6
1

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}`);
      });
gtamborero
  • 1,881
  • 18
  • 21
  • I do have a question in regards combination of the label and input options. Can you please help here https://stackoverflow.com/questions/65566877/align-label-and-select-dropdown-in-the-same-row-in-the-sweetalert-2 – app Jan 04 '21 at 17:31
0

check this out https://sweetalert2.github.io/

"AJAX request example" + "Chaining modals (queue) example" has inputs and you can work with them

0

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");
});
Jaydeep Pandya
  • 807
  • 1
  • 10
  • 24
0

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

}

-1

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");
                });
Rodrigo Butta
  • 301
  • 3
  • 7
  • Kindly read the title before answering any Question, back to you answer "SweetAlert prompt with TWO input fields" and your code is only one input field. – Ad Kahn Oct 31 '19 at 07:50