'How to trigger 'submit' event before the 'blur' event is triggered?
I have a form which has an error message as shown in the example below:
http://codepen.io/anon/pen/dYWyEM?editors=101
Steps to reproduce the problem is as follows:
After opening the codepen link,
Focus in the input field
Press submit button
Since, blur event is triggered first, the error message is made hidden first, thus the position of the submit button is changed. Thus the click event is not registered at all and I need another click to submit the form.
Is there any way to send the submit event first?
Somehow I need to detect the target that triggers the blur event.
It seems that relatedTarget
enables us to figure out the element that triggered the blur event. However, this does not work in Firefox.
Is there way to figure out the relatedTarget
in all browsers?
Solution 1:[1]
If your intention is to perform field validation on blur, you still need a way to check to see if there are any validation errors on form submit, so that you avoid submitting the form while there are validation errors.
I'm therefore suggesting an alternative approach instead of a workaround/fix to your exact problem because I think the current model might be troublesome to begin with.
Why don't you perform all field validations on form submit instead of field blur and then prevent the submission when any of the fields have a validation error?
Solution 2:[2]
Based on what was told in this answer I came with this solutio. Listen to the mousedown
event that triggers before blur
and check if the user can submit the form based on if the error message is visible or not.
form.on('mousedown','input[type="submit"]', function(e) {
if(!errorMsg.hasClass("hidden")){
e.preventDefault();
alert("Can't submit until the error message is gone");
}
});
I have updated your CodePen.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ates Goral |
Solution 2 | Community |