I have some input
box in which I am having onBlur
function called for validation.
The problem I am facing is that when I directly click on submit button without tabbing out from the
input
box, form is getting submitted beforeonBlur
function call and the validation is not happening.
Can someone suggest a workaround here. I am using javascript and JQuery in my JSP page.
There may be simpler options, but you could stop the submit button and then submit the form on the next frame (using setTimeout):
e.g. something like
$('input[type=submit]').click(function(e){
var $form = $(this).closest('form');
e.preventDefault():
setTimeout(function(){
$form.submit();
}, 0);
});
The problem then is how to allow Enter
key form submission to work, if you are on the field you want to validate when you press Enter
. You should probably also validate the entire form on submit
too.
I came up with the following, using the submit event instead (so Enter
is handled) and toggling a class on the form
(to avoid recursion), which should do what you want:
$('form').submit(function (e) {
var $form = $(this);
$form.toggleClass('ignore');
if ($form.hasClass('ignore')) {
e.preventDefault();
$form.find('input[type=text]').blur();
setTimeout(function () {
$form.submit();
}, 0);
}
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/7uLfra3b/2/
You can make the new version more efficient by only blurring the current focused input in the submit handler, but it now allows for Enter
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With