Search code examples
javascriptjqueryformsonclickonblur

Exclude form button from 'onblur' event, JavaScript


I have a form that uses onblur for most of the input fields, like follows:

<form>
<input name="..." id="..." onblur="myFunction(name)" />
<button id="..." onclick="submit()">Submit</button>
</form>

The form validates certain fields (i.e. username, email) in real time via the onblur events, but the same check happens when the user clicks the submit button.

Currently, when the user clicks the submit button, the onblur event is first triggered, and then the onclick event from the button is triggered - thus running the check twice and wasting a couple extra seconds.

Is there any way to override the onblur method to exclude the blur that happens when the user presses the submit button?

I was thinking a simple if(/*button is clicked*/){} within myFunction(), but I wouldn't know how to check for the button click. And it seems, based on the current performance, that the button click is not even registered until after the blur.

Thanks in advance.


Solution

  • You could do this:

    HTML

    <form>
       <input type="text" name="name" id="id" />
       <input type="submit" />
    </form>
    

    jQuery

    $(document).on('blur', 'input:not([type="submit"])', function(e) {
       var key = e.keyCode;  // the key pressed
       var elem = e.target;  // the element blurred 
       myFunction(name);
    });
    
    $(document).on('click', 'input[type="submit"]', function() {
       submit();
    });