2
我寫了一些jQuery來驗證我的Bootstrap表單,但是我遇到了一些問題。Bootstrap jQuery - 空字段驗證問題
首先,如果用戶在不輸入任何內容的情況下單擊輸入字段,我想要一個紅色輪廓出現:JSFiddle example here。在這個例子中,我使用Bootstrap Validator plugin,但是我想在不使用插件的情況下模仿這種效果。
其次,與我剛剛提到的問題有關,綠色大綱只有在用戶點擊提交按鈕後纔會出現,因此用戶在重定向之前只能看到它半秒左右,這使得它有點毫無意義。再次,這可以通過用戶點擊輸入後出現錯誤/成功輪廓來解決。如果有人能幫助我,將不勝感激。
這是我的代碼至今:
HTML:
<form id="auth_form" action="action.php" method="post">
<div class="form-group has-feedback" name="auth_code" id="auth_code">
<label for="auth_code" class="control-label">
Authorisation Code</label>
<input class="form-control" id="auth_code_input" name="auth_code_input" type="password">
<span class="form-control-feedback glyphicon" id="iconBad"></span>
</div>
<div class="form-group">
<div>
<button class="btn btn-info" name="submit" type="submit" id="submit">Submit</button>
</div>
</div>
</form>
的jQuery:
$(document).ready(function() {
$('#auth_form').on('submit', function(e) {
var auth_code = $('#auth_code_input').val()
if (auth_code=="") {
$('#auth_code').addClass('has-error');
$('#iconBad').removeClass('glyphicon-ok').addClass('glyphicon-remove');
e.preventDefault();
} else {
$('#auth_code').removeClass('has-error').addClass('has-success');
$('#iconBad').removeClass('glyphicon-remove').addClass('glyphicon-ok');
}
})
})
完美,謝謝。 – sinesine
您的歡迎:) –
由於某些最佳原因,您可以使用一個簡單的函數來將以下答案分解並在事件'submit'和'blur'中調用它,以便如果有任何更改,您希望這樣做將會完成一次你不應該重複它 – PacMan