Link to home
Start Free TrialLog in
Avatar of msalamon
msalamon

asked on

onblur and onkeypress: onblur triggered on each keystroke when both events are included

I am trying to build an input validation function that will be called either when the user leaves the text field or when the user hits <enter> inside the tex field.  In order to do that, I need to have the function (or two functions) called when 2 types of events are triggered:  onblur (for when the text field loses focus) and onkeypress (where I can check if the keycode == 13, and, if it does, to try to validate; if the keycode != 13, I ignore it).

What I am discovering is that when I add the onblur event to the text field, it is only triggered when the text field loses focuses.  Similarly, if the keycode is the only event, it gets called on every keystroke.  However, if I have both events inside the <input> tag, then the onblur event is triggered BOTH on every keystroke and when the text field loses focus.  This means when the user types a keystroke, first the onblur event is triggered then the keystroke event is triggered.  (I am using IE6).

Is there any way to include both events but to have them triggered for the appropriate reasons and not to have the onblur event triggered from keystrokes?
Avatar of Zvonko
Zvonko
Flag of North Macedonia image

I cannot verify your observation in my IE6.0
Do you perhaps use alert() in your onkeypress handler? Then of course you have every time a blur.

Check this:

<html>
<body>
<form>
<input type=text name="Input" onBlur="window.status+='blur;'" onKeyPress="window.status+='press;'">
</form>
</body>
</html>

Avatar of msalamon
msalamon

ASKER

Needless to say, you're a genius!  Thanks.  However...

In the situations where the text entered is not validated, i use aler() to inform the user of the type of error.  Thus, in situations where the user hits <enter> and the text is not validated, an alert is issued.  This triggers onblur, which calls the function, and then the function is called again, so the alert is shown twice. Is there any way to "smother" the triggering of onblur when alert() is called, or to detect that onblur has been called by an alert so I can ignore it, or something similar to that?
One more thing.  When the user hits <enter>, whether it is validated or not, the text inside the text field disappears.  Any idea how to stop that?
ASKER CERTIFIED SOLUTION
Avatar of Zvonko
Zvonko
Flag of North Macedonia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial