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

后端 未结 2 2050

I have something like:




        
相关标签:
2条回答
  • 2021-02-14 10:37

    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();
    }
    
    0 讨论(0)
  • 2021-02-14 10:39

    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.

    0 讨论(0)
提交回复
热议问题