[英]disable submit button if there is validation errors in form inputs with jquery
如果使用jquery從表單輸入中出現驗證錯誤,我想禁用“提交”按鈕。 以下是我正在使用的代碼: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>
JS:
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
}
});
});
更新:禁用按鈕沒有問題。 問題在於,糾正錯誤后,再次禁用的屬性仍然存在! 我究竟做錯了什么?
您不是從_checkForm(){}
函數返回結果。 您可以通過_validate
,然后將其傳遞給它,但是您不使用/傳遞_checkForm()
的結果,因此需要進行以下驗證:
if(!_checkForm()) {...}
始終為true,因為_checkForm
返回任何內容(未定義),而您的!
-ing。 另外,如果檢查通過,則應return false
來中斷提交。
您忘記了返回false。
請嘗試以下操作:
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
}
});
});
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.