首页 > 解决方案 > 同时使用危险模式和输入 - sweetalert

问题描述

我使用 Sweet Alert,所以在执行危险操作之前,我会弹出对话框。例子。

swal({
  title: "Are you sure?",
  text: "Once deleted, you will not be able to recover this imaginary file!",
  icon: "warning",
  buttons: true,
  dangerMode: true,
})
.then((willDelete) => {
  if (willDelete) {
    swal("Poof! Your imaginary file has been deleted!", {
      icon: "success",
    });
  } else {
    swal("Your imaginary file is safe!");
  }
});

但用户可以根据需要输入任何备注,是可选的,不是必需的。所以会变成这样

在此处输入图像描述

所以我修改了这样的代码

function RequestUpload(value) {

                swal({
                    title: "Are you sure?",
                    text: "Are you sure want to request to upload?",                   
                    icon: "warning",
                    buttons: true,                   
                    dangerMode: true,
                    content: {
                        element: "input",
                        attributes: {
                            placeholder: "Any remarks?",
                            type: "text",
                        },
                    },
                })
                    .then((willDelete,input) => {
                        if (willDelete) {

                            swal(`You typed: ${input}`);
                            //Call ajax here

                            
                        }
                        else {
                            swal(`Is not delete`);
                        }
                       
                    });

            
            }     

但我无法从输入中获取值,它保持显示undefined

在此处输入图像描述

知道如何解决这个问题吗?

标签: javascriptjquerysweetalert

解决方案


输入值作为第一个参数提供。当您单击取消,单击弹出窗口外部或按ESC时,您将获得null将关闭警报的值(即:触发您的 else)。否则,如果您单击“确定”,它将保留您的输入值:

.then((input) => {
  if (input !== null) {
    swal(`You typed: ${input}`);
    //Call ajax here
  } else {
    swal(`Is not delete`);
  }
});

function RequestUpload(value) {
  swal({
      title: "Are you sure?",
      text: "Are you sure want to request to upload?",
      icon: "warning",
      buttons: true,
      dangerMode: true,
      content: {
        element: "input",
        attributes: {
          placeholder: "Any remarks?",
          type: "text",
        },
      },
    })
    .then((input) => {
      if (input !== null) {
        swal(`You typed: ${input}`);
        //Call ajax here
      } else {
        swal(`Is not delete`);
      }
    });
}

RequestUpload();
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>


推荐阅读