Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How on trigger onBlur before form submit

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 before onBlur function call and the validation is not happening.

Can someone suggest a workaround here. I am using javascript and JQuery in my JSP page.

like image 540
Zeeshan Avatar asked Sep 29 '22 22:09

Zeeshan


1 Answers

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.

like image 150
Gone Coding Avatar answered Oct 05 '22 00:10

Gone Coding