javascript - Can not stop submit event in Javascript
问题描述
I used this to validate my form but I can stop the submit event on my page. It still sends data and submit that. Why? How can I stop it?
$(document).on("submit", "form", function(e) {
if ($('#input-name').val() === '' && $('#input-phone-number').val() === '' && $('#input-address').val() === '' && $('#input-email').val() === '') {
e.preventDefault();
$('.noti-container').css({
'opacity': '1',
'z-index': '9999',
'top': '20px',
'background': '#FFCCCC'
});
$('.icon-container').html('<i class="fa fa-close"></i>');
$('.notif').text('Please fill all field!');
$('.notif').css({'color': 'black'});
$('.icon-container').css({
'background': '#F2F5A9'
});
setTimeout(function () {
$('.noti-container').css({
'opacity': '0',
'z-index': '-1',
'top': '0',
})
}, 1500);
return false;
} else {
return true;
}
});
解决方案
e.preventDefault();
似乎存在于 if 块中。如果if 条件解析为 false,则将提交表单。您需要e.preventDefault();
在 if 块之前移动代码以防止在所有情况下提交。
例子:
$(document).on("submit", "form", function(e) {
e.preventDefault();
// Remaining Code
}
推荐阅读
- google-apps-script - 在 Google Apps 脚本中,是否可以使用 try/catch 捕获超时,或者它是否发生在更高级别?
- javascript - 使用猫鼬在 mongodb 中按月收集?
- java - 如何处理具有 2 个输入和 2 个输出的过程的错误异常?
- flutter - 如何在 Flutter 中为这个 api 数据添加分页?
- python - 无法使用以下 python 代码保存文件。AttributeError:“数组”对象没有属性“保存”
- python - 从 python 自动创建容器
- python - 当我运行此代码时,它显示无效参数
- javascript - 关于 JS 中的“包装器对象”的这种观点是否属实
- .net-core - AutoMapper 9 通用扩展静态类
- python - 使用 Exif 元数据获取图片的唯一 ID