I have something like:
<input type="textbox" id="partNumber" onChange="validatePart(this);">
<input type="textbox" id="quantity" onfocus="saveOldQuantity(this);">
The onChange event is properly firing after a change is made and the textbox loses focus. When quantity gains focus, the onfocus event is properly firing to save the old value of quantity before changes are made.
If validatePart() detects an invalid partNumber value, it alerts the user to that fact. After the alert() has cleared, I’d like to return focus to the partNumber input. But doing a focus() on the input node is not giving it focus. Debugging is tricky here, because the IE debug window interaction is, of course, changing the focus.
How can I ensure focus returns to partNumber if an error is detected in validatePart()?
EDIT:
A simple version of validatePart():
function validatePart(node) {
if (!node.value) {
alert('Please enter a part number.');
node.focus(); // <======= why isn't this having any effect??
}
}
Adding a small timeout and resetting the focus back to the
partNumbertextbox should do the trick.Thus your
validatePart()function becomes something like:Here’s a quick “live” example that simply fires an
alertno matter what is entered into thepartNumbertextbox and successfully returns focus back to thepartNumbertextbox (even if you tab off it to thequantitytextbox.