简体   繁体   中英

Javascript - set focus after alert message

I'm tryng to focus on the same element when validation fail. Here's my HTML code :

<input id="potatoes" name="potatoes" value="" type="text" class="tooltip" onblur="Validate('potatoes')" autocomplete='off'>

and here's my javascript code :

function Validate(id) {
var errors = {
    potatoes : 'enter potatoes',
    hamburgers : 'enter'
};
if (document.getElementById(id).value === '') {
    if (id in errors) {
        alert(errors[id]);
         //setTimeout(function(){document.getElementById(id).focus();}, 1);
    }
} 

}

I've tried to set focus using .focus() method but it doesn't work. I've read that it might depend on "onblur" in HTML, when I call my function Validate(), so i've tried to change it but nothing worked till now.

There is a problem here. This code is going in loop. When 'focus' is triggered, the function Validate is called again, showing another alert dialog.

That's a working code

HTML

<input id="potatoes" name="potatoes" value="" type="text" class="tooltip" onblur="Validate(this)" autocomplete='off'>

Javascript

var validating = false; //<-- IMPORTANT
function Validate(element) {
var id = element.id;

var errors = {
    potatoes : 'enter potatoes',
    hamburgers : 'enter'
};
if (document.getElementById(id).value === '') {
    if (id in errors) {
            if(validating == false) {
                    validating = true
            alert(errors[id]);
            setTimeout(function(){
                document.getElementById(id).focus();
                validating = false;
            }, 1);
            }
    }
}
} 

In the html I'm passing this , doing so I'm passing the element and in the Validate function you can access to the id just calling

var id = element.id;

For the focus problem (caused by a loop problem) as you can see I'm using a validating variable to know when is validating when is not. This let Validate function avoids to go in loop. So:

1) Define a validating var outside the Validate function and set it to false.

2) Fire the focus and alert only if validating is false, and after that set it to true

The javascript function alert(string) is synchronous. The script is paused while the user is reacting to the alerted message. There is no need to do something special. The following snippet should work:

alert(errors[id]);
document.getElementById(id).focus();

The element got focus directly after the user has submitted the alerted message.

你可以像这样使用 jQuery:

setTimeout(function() {$('#yourInputId').focus();},1);

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