我正在使用此JS validate plugin并且它正在运行,但它会截取页面中的所有按钮点击,并且即使点击Back to Home
也会尝试验证表单。
我只想在单击login
按钮时验证表单,当我单击Back to Home
按钮时,我不需要验证表单,只需提交并重定向到主页。 / p>
我仍然在Back to Home
点击事件上提交表单的原因是因为我需要捕获电子邮件地址以便在我的控制器中使用。
如何才能捕获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>
答案 0 :(得分:1)
发生这种情况的原因是因为您将任何按钮的点击事件与.btn
类绑定在一起。
要避免这种情况,您可以通过向包含id
和form-group
按钮的login
添加back to home
来仅绑定所需按钮的点击事件。< / p>
<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();
});