Reputation: 2772
So I have two text elements A and B, and on the onblur event of both objects I have the same validation function that will popup a message if B (a date field) is wrong. Now, If I change A, and then select B, it will run the function twice. it seems it runs it once for the onblur of both A and B. This causes the user to get the same error message twice.
What do I need to do to force the onblur of A to not allow any other events to kicked off?
Here is an exmaple code i made up. If you are on the 2nd field, and try to go to the first, if will run the function twice
function myVal(){
if (document.getElementById("B").value == 'Z') {
alert('Bad Value');
document.getElementById("B").focus();
}
}
<form>
<input name="A" value="A" onblur="myVal();"/>
<input name="B" value="Z" onblur="myVal();"/>
</form>
Upvotes: 0
Views: 441
Reputation: 185913
Consider this solution:
Live demo: http://jsfiddle.net/SCsX2/
Another thing, this focus() thing is not desirable (at least that's how I feel). The red message should be enough:
Better live demo: http://jsfiddle.net/SCsX2/2/
You can even run the validation code on each input-box keyup event. That will make the error message more responsive:
Even better live demo: http://jsfiddle.net/SCsX2/3/
Upvotes: 1
Reputation: 66389
The function does not run twice, but by setting focus on the second field you force the user to stay there forever, or until he type correct value.. i.e. you have the user hostage.
Try to remove or comment the .focus()
line and see if it's helping.
Upvotes: 1
Reputation: 63519
Does the same thing happen without the alert()
call? alert()
steals focus, causing whatever was previously focused to blur.
Upvotes: 0