带有两个输入框的SweetAlert提示框

25

目前正在进行个人项目开发。我希望用户点击按钮后,会出现一个SweetAlert提示框,用于验证他们的凭据。然而,我在SweetAlert网站上看到的代码只允许一个输入字段。以下是我目前拥有的代码:

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

那么,我能否获得两个输入字段呢?一个输入字段用于密码,另一个输入字段用于文本。


我已经fork了它,我会看看能否为您提供支持多个输入字段的版本。 - Zachrip
那太好了,@Zachrip。 - ballerz
16个回答

41

现在 SweetAlert2 已经发布了:https://sweetalert2.github.io

根据他们底部的信息:

不支持多个输入框,但你可以通过使用 html 和 preConfirm 参数来实现。在 preConfirm() 函数中,你可以将自定义结果作为参数传递给 resolve() 函数:

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)

那如果在这些情况下我也需要验证呢? - Pardeep Jain
@PardeepJain,请查看我的答案,我编辑了Tikky的示例以包括验证 https://dev59.com/G1wZ5IYBdhLWcg3wbv7r#62244976。原始答案的信用仍归Tikky所有。 - Christopher Smit
@Tikky这很有启发性。我有一个关于标签和输入选项组合的问题。你能否在这里帮助我 https://stackoverflow.com/questions/65566877/align-label-and-select-dropdown-in-the-same-row-in-the-sweetalert-2 - app

10

不支持多个输入,您可以使用HTMLpreConfirm参数来实现它们。 在preConfirm()函数中,您可以返回(或如果是异步操作,可以用resolve)自定义结果:

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>

来源: 输入类型


10

根据Tikky在他们的回答中发布的示例以及问题所要求的验证,您可以尝试以下方法来实现该方法的验证:

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)

这是一篇很有信息量的文章。我有一个关于标签和输入选项组合的问题。你能在这里帮忙吗?https://stackoverflow.com/questions/65566877/align-label-and-select-dropdown-in-the-same-row-in-the-sweetalert-2 - app

8
你可以在默认的SweetAlert类型中输入内容,只要将html属性设置为true即可。问题在于,除非类型设置为“input”,否则SweetAlert会向输入字段添加display: none
这有点麻烦,但你可以在js文件中更改此设置。
<input type=\"text\" tabIndex=\"3\" />\n

为了

<input id=\"swalInput\" type=\"text\" tabIndex=\"3\" />\n

修改css文件:

.sweet-alert input {

to

.sweet-alert #swalInput {

那么,当您调用时,只需将您的HTML添加到文本参数中,如下所示:
swal({
    title: "Log In to Continue",
    html: true,
    text: "Username: <input type='text'><br>Password: <input type='password'>"
});

这种方法只是指定只有由SweetAlert生成的输入才会被这样样式化,因此您添加到文本中的任何输入都不会受到该样式的影响。


7
据我所知,您无法使用现成的解决方案来实现此功能。您可以选择分支并实现,或者只需将HTML元素用作模态框(例如,如Bootstrap的模态框中所示)。

3
现在,您可以使用sweetalert2和{content:anHtmlElement}来实现此功能。请参阅下面的帖子。 [SweetAlert 2文档] (https://sweetalert.js.org/docs/#content) - Stan
感谢 @Stan!SweetAlert 1.x和2.x有不同的规格。这里混合使用了SweetAlert 1.x和2.x。html在2.x中无法工作,所以必须使用内容。 - gtamborero

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

请在第6行的末尾添加一个逗号 => 类型:"input" - Haseeb Zulfiqar

2

不支持多个输入,但可以使用html和preConfirm参数来实现它们。请注意,在preConfirm函数中,您可以将自定义结果传递给resolve():

您可以按照以下方式进行操作:

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/

我尝试了这个例子(https://jsfiddle.net/03bbuo8t/),但是出现了错误ReferenceError: result未定义。 - Mistre83
你正在使用Sweet Alert还是Sweet Alert 2? - Abhradip
我正在使用 Sweet alert 2。 - Mistre83
省略 if 条件中的结果,用“true”代替。 - Abhradip
并将$('#swal-input1').val()和$('#swal-input2').val()替换为document.getElementById('swal-input1').value和document.getElementById('swal-input2').value,分别。 - Abhradip

2
通过使用sweetalert2中的preConfirm方法和将ok按钮作为提交按钮,非常简单。"Original Answer"翻译成"最初的回答"。
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 
                     }
         })

这是一篇很有信息量的文章。我有一个关于标签和输入选项组合的问题。你能帮忙解答一下吗?链接在这里:https://stackoverflow.com/questions/65566877/align-label-and-select-dropdown-in-the-same-row-in-the-sweetalert-2 - app

1

这里是一个使用sweetalert@^2.1.0的示例,展示了一种拥有多个输入字段的方法。该示例使用jQuery,但不需要jQuery即可使用此技术。

// ==============================================================
//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());

1
在SweetAlert 2.x中,您可以使用这个原生JavaScript来获取/设置一个输入框。您可以将更多元素链接到内容中,以便拥有多个输入框:
  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}`);
      });

我有一个关于标签和输入选项组合的问题。你能帮忙看一下这里吗?https://stackoverflow.com/questions/65566877/align-label-and-select-dropdown-in-the-same-row-in-the-sweetalert-2 - app

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接