Click to See Complete Forum and Search --> : focus not being set -- what am I missing?


dfh123
11-19-2003, 09:03 PM
Here is a snippet of a function to validate a numeric field in my code:

function Number_Validate(theField, len) {
var n = theField.value;
var numpattern = /\D+/

if (n=="") return(true);
if (n.match(numpattern)) {
alert ("This field must be numeric.");
theField.focus();
theField.value="";
return(false);
}
...
}

Then in my html form, I have a series of text boxes, such as this:

<INPUT type="text" onChange="Number_Validate(this,3)"
...

The validation works; that is, when I enter bad data and then hit a tab key or click the mouse to move out of the field, the alert box pops up. However, when I close the alert box, the focus is set to the *next* field, not the one that had the error. Setting the value to null on the error field works, so I know the code is executing. I get no error messages.

Why am I unable to get the focus set on the field I want?

Thanks in advance.
-don

Khalid Ali
11-20-2003, 06:37 AM
change onchange event call to
onkeyup

and everything should be fine

dfh123
11-20-2003, 06:53 AM
Thanks for the suggestion, but this does not do what I want: the field must be, say, 3 characters long. Using OnKeyup tries to validate after each character, so finds first entry "invalid" since it's too short. I really want to examine the field after the user has "finished" with it, which is when he hits tab or mouses to another place.

Still hoping there's some way to get that focus back to a field after tabbing out of it.

-don

dfh123
11-20-2003, 07:29 AM
Khalid-

After your suggestion about changing the event that triggers the validation, I went (again) through a search of this forum's archives, with different keywords. I found a suggestion, which in fact works:

I changed the "onchange" to "onblur". I'm guessing that this gets invoked before the focus actually leaves the field. It does what I want.

I'm still left with the lingering question of why setting the focus from the onchange doesn't work -- shouldn't I be able to move the focus around to any field from any place? But for now, I'm happy! :cool:

Thanks again for your interest & response.
-don