我有一个带有onsubmit =“ return validate();”的表单,该表单可以验证表单的所有输入是否完整,如果不完整,则用户可以选择继续。
问题是,当验证字段为空时,将显示警报,但随后发送表单,而没有给我机会在甜蜜警报选项之间进行选择
function validate() {
var errors = 0;
$("#form :input").map(function(){
if( !$(this).val() ) {
errors++;
}
});
if(errors > 0){
Swal.fire({
title: '¿Are your sure?',,
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
cancelButtonText: 'Cancel',
confirmButtonText: '¡Yes!',
allowOutsideClick: false
}).then((result) => {
if (result.value) {
return !0
} else {
return !1
}
})
}
return !0
}
答案 0 :(得分:1)
Sweet警报是异步的,不会阻塞包含方法的流程,请将它与同步并会阻塞流程的标准确认进行比较。
考虑使用正常的按钮(如果有效),该按钮将调用Submit,而不是使用Submit按钮。
//Wire up the event handler
$("#submit").on("click", validate);
function validate() {
var errors = false;
//use each instead of map here.
//break out after first error
$("#form :input").each(function() {
if (!$(this).val()) {
errors = true;
//Breaks the loop
return false;
}
});
if (errors) {
Swal.fire({
title: '¿Are your sure?',
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
cancelButtonText: 'Cancel',
confirmButtonText: '¡Yes!',
allowOutsideClick: false
}).then((result) => {
if (result.value) {
//Programatically submit form
$("#form").submit();
}
});
} else {
$("#form").submit();
}
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/8.11.8/sweetalert2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/8.11.8/sweetalert2.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form">
<input type="text" name="bob" />
<input type="button" value="Submit" id="submit">
</form>