简体   繁体   中英

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.

There may be simpler options, but you could stop the submit button and then submit the form on the next frame (using setTimeout):

eg 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 .

may be you can disable the submit button when input is on focus, and enable it when input is on blur, something like this:

$('input').focus(function(){
  $('submit').attr("disabled", true);
}).blur(function(){
  $('submit').attr("disabled", false);
});

Hope this can help you :)

please see this example.

  $('#blurtest').blur(function(){ $('#bluredText').html($(this).val()); }); $('#testform').submit(function(e){ $('#blurtest').trigger('blur'); $(this).submit(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> Blured Text: <span id="bluredText"></span> <form name="testform" id="testform" action="" method="post"> <label>Enter Text:</label> <input name="blurtest" id="blurtest" value="" /> <input name="submit" id="submit" value="Submit" type="Submit"/> </form> 

http://jsfiddle.net/narayand4/xvf2x7ee/22/

i think you can solve your issue like this way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM