我有一个带验证的表单:
<form role="form" method="POST" action="" >
<input type="password" class="form-control top-buffer-sm" placeholder="Password" name="password" required autofocus></input>
<input type="email" class="form-control top-buffer-sm" placeholder="Email" name="email" required autofocus></input>
<div class="modal-footer">
<button id="createUser" type="submit" class="btn btn-primary">Create</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
我的提交按钮有一个ID,我需要在提交表单之前做一些其他功能:
$('#createUser').click(function(){
//check to see if validation passed
//do custom stuff
//now make ajax call
$.ajax();
});
但是如果表单无效,我的ajax调用仍在进行中,当然会导致服务器错误。当我单击提交按钮时,如何检查表单是否通过了验证?感谢
答案 0 :(得分:2)
为什么不在表单上列出提交事件?
<form role="form" method="POST" action="" id="myForm">
然后:
$('#myForm').on('submit', function(event) {
// Prevent form submission on click
event.preventDefault();
// Write the code the determins if the form is valid.
// `this` refers to the form.
if (formIsValidCondition) {
// do Ajax call here
} else {
// Do return a response to the user
return false;
}
});
答案 1 :(得分:-1)
这是我的答案:
$('#createUser').click(function(){
var valid = $("form").valid();
if (valid)///keep on trucking