Tiz
Tiz

Reputation: 423

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.

Upvotes: 1

Views: 26885

Answers (3)

Robert Yeomans
Robert Yeomans

Reputation: 376

You can use jQuery like this:

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

Upvotes: 0

Alvise Susmel
Alvise Susmel

Reputation: 569

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

Upvotes: 7

ˈvɔlə
ˈvɔlə

Reputation: 10252

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.

Upvotes: 3

Related Questions