[英]How to prevent submit but still validate required fields?
I have a form, and when is submitted I prevent it with e.preventDefault()
, but I still want the browser to validate the required fields before I make the AJAX call. 我有一个表单,当提交时,我可以使用
e.preventDefault()
阻止它,但是我仍然希望浏览器在进行AJAX调用之前先验证必填字段。
I don't want to get fancy with javascript validation, I just want the browser to validate the required fields (HTML5). 我不想看待JavaScript验证,只希望浏览器验证必填字段(HTML5)。
How can I achieve this? 我该如何实现?
It works, even if you don't do the checkValidity
check. 即使您不执行
checkValidity
检查,它也可以工作。 In chrome, it won't call the submit function on the form if form is not valid: 在chrome中,如果表单无效,它将不会在表单上调用Submit函数:
$(document).ready(function(){
$("#calendar_form").submit(function(e){
e.preventDefault();
calendarDoAjax();
});
function calendarDoAjax(){
var proceed = false;
if( $("#calendar_form")[0].checkValidity ){
if ($("#calendar_form")[0].checkValidity()) {
proceed = true;
}
}else{
proceed = true;
}
if (proceed) {
//Do ajax call
}
}
});
Add this in the end of your submit function: 在您的Submit函数的末尾添加:
if (evt && evt.preventDefault) {
evt.preventDefault();
} else if (event) {
event.returnValue = false;
}
return false;
And pass the var evt
in your function like this: 然后像这样在函数中传递var
evt
:
function(evt) { /* Your Code */ }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.