如果使用jquery表单输入有验证错误,我希望禁用submit按钮。下面是我正在使用的代码: HTML:
<form action="/order" id="orderForm" class="orderform" autocomplete="off" method="post" accept-charset="utf-8">
<div class="orderform-inner">
<ol class="questions" id="questions">
<li>
<span><label for="oName">Please enter your name or the company name</label></span>
<input class="finput" id="oName" name="oName" type="text" maxlength="20"/>
<span class="input-error"></span>
</li>
</ol>
</div>
<button name="submit" class="submit" type="submit">Submit</button>
</form>
联署材料:
function _validate(input) {
if( input.val() === '' ) {
_showError(input, 'EMPTYSTR');
return false;
}
return true;
}
function _checkForm() {
$('#orderForm .finput').each(function(){
$(this).focusout(function() {
_validate($(this));
});
});
}
$(document).ready(function() {
_checkForm()
$('form#orderForm').submit(function(event) {
event.preventDefault(); // for ajax submission
if(!_checkForm()) {
$('button.submit').prop('disabled', true);
}
else {
// ajax post
}
});
});
更新:禁用按钮没有问题。问题是,在纠正错误之后,禁用的属性仍然存在!我做错了什么?
发布于 2015-10-13 03:17:17
您不会从_checkForm(){}
函数返回结果。您可以从_validate
one中进行操作,并将其传递给它,但是您并不使用/传递来自_checkForm()
的结果,因此这个验证:
if(!_checkForm()) {...}
总是正确的,因为_checkForm
不返回任何内容(未定义),并且!
-ing它。此外,如果检查通过,您应该使用return false
来中断提交。
发布于 2015-10-13 03:18:02
你忘记了回报是假的。
请试试这个:
function _validate(input) {
if( input.val() === '' ) {
_showError(input, 'EMPTYSTR');
return false;
}
return true;
}
function _checkForm() {
$('#orderForm .finput').each(function(){
$(this).focusout(function() {
_validate($(this));
});
});
}
$(document).ready(function() {
$('form#orderForm').submit(function(event) {
event.preventDefault(); // for ajax submission
if(!_checkForm()) {
$('button.submit').prop('disabled', true);
return false;
}
else {
// ajax post
}
});
});
发布于 2015-10-13 03:28:23
test1.html
function _validate(input) {
if( input.val() === '' ) {
_showError(input, 'EMPTYSTR');
return false;
}
return true;
}
function _checkForm() {
$('#orderForm .finput').each(function(){
$(this).focusout(function() {
_validate($(this));
});
});
}
$(document).ready(function() {
_checkForm();
$('form#orderForm').submit(function(event) {
event.preventDefault(); // for ajax submission
if(!_checkForm()) {
$('button.submit').prop('disabled', true);
}
else {
// ajax post
}
});
});
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
<form id="orderForm">
<input class="finput">
<button class="submit">submit</button>
</form>
<script type="text/javascript" src="test1.js"></script>
</body>
</html>
https://stackoverflow.com/questions/33101200
复制