Reputation: 426
I have a form with fields that are validated on submit. If a field fails validation a text i placed below the field (bootstrap form-group and help-block is used)
When the user changes the field value, then the help-block should be hidden.
<input type="email" class="form-control" id="email" placeholder="Email">
<span class="help-block error-block collapse in">Invalid email</span>
The problem is that when hiding the help-block, then all elements below is moved up. So if the user changes the field and click the submit button, then (sometimes) only the onchange event is fired.
On this page I'm only able to reproduce the problem i Chrome: http://codepen.io/casper-skovgaard/pen/mEBaZJ?editors=1111
Enter some text i the email field and click the submit button. Only onchange is fired.
How can I make sure that onsubmit is always fired?
Upvotes: 1
Views: 344
Reputation: 81
You could try removing the classes and collapsing the error message after a timeout. Using a timeout without a delay value the browser will manage this delayed task and it will process the click on the button before it starts the collapse animation.
http://codepen.io/ldlharper/pen/zBEyyV?editors=1111
setTimeout(function() {
$control.closest('.form-group').removeClass('has-error').removeClass('has-success');
$control.closest('.form-group').find('.error-block').collapse("hide");
});
Upvotes: 2
Reputation: 924
the problem seems to be that the change event gets fired when the focus left the text field (right after blur), which then moves the button up - so there is no button at the point where the click event occurs (like you described already).
I think there is no direct solution, but possible workarounds:
Either You could just not hide the error message directly, but on submit: e.g. two form fields have errors - both marked with the error class, when the user clicks the submit button you could revalidate the fields, and hiding / displaying the error-messages as required.
Or you could use another event instead of "onchange". E.g. you could use "onkeyup" which causes the error message to disappear while the user enters something into the box - so there is no possibility to hit button during animation. It worked for me, when I changed:
$("input").change(...)
to
$("input").keyup(...)
Upvotes: 0