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>
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/