我希望用户能够点击提交,但是如果没有填写正确的字段,它将不会通过并且会出现错误。这可能吗?我知道如何处理错误部分,但阻止提交部分很烦人。
5 回答
处理表单上的提交事件:
$(document).ready(function() {
$("#yourFormIdHere").submit(function(e) {
// process fields
if (thereWereErrors) {
e.preventDefault();
}
});
});
如果您在事件处理程序中调用该event.preventDefault()
方法,它会阻止该事件的默认操作发生,在提交事件的情况下,默认当然是提交表单...
This is what you want: (I reckon) working demo http://jsfiddle.net/8YsAx/
Good link: http://docs.jquery.com/Plugins/Validation
API: validate
http://docs.jquery.com/Plugins/Validation/validate#options
Hope it fits the cause :)
script
<script type='text/javascript' src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
code
$(document).ready(function(){
$("#registerForm").validate();
});
<form method="post/get" action"url" onsubmit="return Validation();">
The onsubmit is called when the submit is clicked. The Validation function should return true for continue and false if you want to prevent the form from being submitted.
您需要在表单中添加一个提交事件监听器:
$('#myForm').submit(function() {
// return true (proceed submit) | false (stop submit)
// In case the form is not valid you can render your errorMessages first
});
如果你问怎么做(而不是你实际问的是“这可能”),那么你可以在你的 jquery 代码中做这样的事情。如果您要提交多个表单,这是一种方法。
if($(your_field_here).html() === '') {
error = 1;
error_field .= "<br />your_field_here is not filled out!";
}
if($(your_second_field_here).html() === '') {
error = 1;
error_field .= "<br />your_field_here is not filled out!";
}
if(error === 1){
$(your_error_field).html(error_field);
} else {
// do your ajax / w.e call here
}
编辑:这是我个人一直在做的事情。如果有更简单的方法,请通过评论告诉我。