View Full Version : setting focus back to same input control via onchange

12-04-2003, 05:00 PM

I'm attempting to do some simple form validation with the onchange event and an onsubmit event. The following test code attempts to validate that the first input field contains a integer. The "validation" portion seems to be mostly working. The only problem seems to be with the focus() called from the onchange event. When called from the onsubmit event, with an invalid (non-numeric) value in the first input field, the user's focus is correctly placed in the errant field follwowing the alert. However, under the same circumstances except using the onchange event (user edit's field and tabs to next entry), the alert is generated, yet the cursor still ends up in the next input field. I'd appreciate any help to correct this minor glitch. BTW, I'm using IE, Mozilla and Netscape for browsers - the Netscape and Mozialla browser appear to place the cursor properly via both the onsumbit and onchange - however, via onchange, the user still has to click in the field before typing - but not so for onsubmit. Here's the code....

<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
function validate( field )
if ( isNaN( parseInt( field.value )) )
alert( "Please enter a valid #" );
return false;
return true;

<body bgcolor="#FFFFFF" text="#000000">
<form action="go.html" name="test" onsumbit="return validate( document.forms[ 'test' ].foo );">
<tr><td><input type="text" name="foo" onchange="return validate( document.forms[ 'test' ].foo );"/></td></tr>
<tr><td><select name="bar" size="4" MULTIPLE>
<option value="One">One
<option value="Two">Two
<tr><td><input type="submit"/></td></tr>

12-04-2003, 07:44 PM
I tested your code out with IE6+ on a Windows2000 machine and it work fine for me. The cursor was returned back to the same input box. I would also recommend that you use field.select() in your function so that it will select the value to be overwritten.

12-04-2003, 09:19 PM

I'm using IE5.5+ and Mozilla 1.5 and Netscape 6.2.2. I'm definately not seeing the bahvior you are in IE though - I wish I could upgrade - not an option given corporate std browser bs....

Any other thoughts?

12-05-2003, 01:54 AM
Works for me in IE5.5. The cursor focuses back to the field.

You should not use parseInt anymore because entering "3d" and the like, validates because parseInt already converted it to "3" causing isNaN to return false.

if ( isNaN( field.value ) )

07-20-2006, 07:05 PM
There is a scenario where the onChange() event can be tricked into allowing invalid characters to be submitted! Keep in mind that the onChange() event is triggered only when there is a change to the text field. If I input invalid text and then get rejected and sent back to the same field again - if I don't make a change (ie - if I keep the same invalid text as before!) the onChange() never fires again.