wiscWeb
wiscWeb

Reputation: 213

Field won't take focus after error

Probably going to be something really obvious that I can't find again. But any help, as always, is appreciated.

My javascript error messages and focus settings work fine with all of the validation functions on submit, but I can't get the field to take focus with the onblur validations. The error message correctly appears but the focus is going to the next field in the form.

Here's my code for the field in question Javascript first:

function validatexxxx()
{
var e = document.getElementById('xxxxNumber');
//check to see if the xxxx number is already in use.
for (i = 0; i < xxxxArray.length;i++) {

if (e.value == xxxxArray[i]) {
    alert("That xxxx Number is already in use!");
        e.focus();
        return false;
    }//end if e.value = xxxxarray 

}//end for loop
var eText = e.value;
if (eText.length >= 15) {

    alert("xxxx Number must be less than 15 characters long!");
    e.focus();
    return false;
}
    return true;

}

And the html where the input is:

<tr><td>xxxx No.: </td><td><input type="textbox" id="xxxxNumber"
name="xxxxNumber" onblur="return validatexxxx();"/> </td> </tr>

Upvotes: 1

Views: 2180

Answers (3)

Claude
Claude

Reputation: 415

Try to put it in a closure like this.

e.focus(function() {
   alert("xxxx Number must be less than 15 characters long!");  
});

Upvotes: 0

mavili
mavili

Reputation: 3424

It's the alert() that's causing the focus to go away. After the popup is displayed, you're setting the focus. But as user needs to click OK in the appeared popup window, the focus is lost.

Upvotes: 3

Pointy
Pointy

Reputation: 413720

Trying to force focus from a "blur" handler is inherently problematic. Try this: wrap you calls to .focus() in a timeout handler. That'll let the "blur" event complete before the attempt to set focus:

setTimeout(function() { e.focus(); }, 1);

Also, alert() can be problematic too, especially in Safari. That browser has (or had, in the past; I haven't tried lately) a tendency to imagine that the appearance of the "alert" window means that the main browser window has lost focus. After that, Safari will completely ignore any calls to .focus(). Your interface would look better with a custom "dialog" scheme, or some other way of reporting validation errors.

Upvotes: 2

Related Questions