[英]JavaScript Validator bind all buttons click event
我正在使用此JS validate插件 ,它正在運行,但是它將攔截頁面中的所有按鈕單擊,並且即使我單擊Back to Home
,也試圖驗證表單。
我只希望表單在單擊“ login
按鈕時進行驗證,當我單擊“ Back to Home
按鈕時,我不需要對表單進行驗證,只需提交並重定向到主頁即可。
我仍在“ Back to Home
單擊事件上提交表單的原因是,我需要捕獲要在Controller中使用的電子郵件地址。
如何僅捕獲“ Login
和“ Back to Home
按鈕的單擊事件?
當我單擊“ Back to Home
按鈕時,是否可以停止驗證表單?
HTML和JS代碼:
<form data-toggle="validator" role="form">
<div class="form-group">
<label for="inputEmail" class="control-label">Email</label>
<input type="email" class="form-control" id="inputEmail" placeholder="Email" data-error="Bruh, that email address is invalid" required>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="inputPassword" class="control-label">Password</label>
<div class="form-group col-sm-6">
<input type="password" data-minlength="6" class="form-control" id="inputPassword" placeholder="Password" required>
<span class="help-block">Minimum of 6 characters</span>
</div>
<div class="form-group col-sm-6">
<input type="password" class="form-control" id="inputPasswordConfirm" data-match="#inputPassword" data-match-error="Whoops, these don't match" placeholder="Confirm" required>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="form-group">
<button type="button" class="btn btn-primary" data-action="login">Login</button>
<button type="button" class="btn btn-danger" data-action="backtohome" >Back To Home</button>
</div>
</form>
<script src="http://127.0.0.1/js/validator.min.js"></script>
<script type="text/javascript">
$('.btn').on('click', function(event) {
event.preventDefault();
var action = $(this).data('action');
if (action !== "nil")
{
$('#action').val(action);
var form = $("form");
form.submit();
}
});
</script>
發生這種情況的原因是因為您將任何按鈕的單擊事件與.btn
類.btn
。
為了避免這種情況,您可以通過將id
添加到包含login
和back to home
按鈕的form-group
,從而僅綁定所需按鈕的單擊事件。
<div id='form-actions' class="form-group">
<button type="button" class="btn btn-primary" data-action="login">Login</button>
<button type="button" class="btn btn-danger" data-action="backtohome" >Back To Home</button>
</div>
修改jQuery以僅捕獲#form-actions
按鈕單擊事件
$('#form-actions button').on('click', function(event) {
event.preventDefault();
var action = $(this).data('action'),
form = $("form");
if (action == 'backtohome') {
$('form').validator('destroy');
}
if (action !== "nil") {
$('#action').val(action);
}
form.submit();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.