简体   繁体   中英

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>

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.

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.

Try to put it in a closure like this.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM