How to give focus() after an alert()?

徘徊边缘 提交于 2020-01-01 04:41:33

问题


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??
    }
}

回答1:


Adding a small timeout and resetting the focus back to the partNumber textbox should do the trick.

Thus your validatePart() function becomes something like:

function validatePart(node) {
    if (!node.value) {
        alert('Please enter a part number.');
        setTimeout(function(){node.focus();}, 1);
    }
}

Here's a quick "live" example that simply fires an alert no matter what is entered into the partNumber textbox and successfully returns focus back to the partNumber textbox (even if you tab off it to the quantity textbox.




回答2:


Your code seems to work as expected for me. See this fiddle. Are you seeing some other behavior? I see that I type a number in textbox1. Then when I tab over to textbox2 I get Invalid Part! error and focus stays on current textbox.

Updated - Since this only seems to play nice in Chrome you could keep track of whether an error exists. If so then handle it.

var error = null;
function checkForErrors() { 
   if (error) { error.focus(); error = null; }            
}

function validatePart(node) {
   if (badpart) { error = node; }
}

function saveOldQuantity(node) {
   checkForErrors();
}


来源:https://stackoverflow.com/questions/7234190/how-to-give-focus-after-an-alert

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!