How to prevent an textfield losing focus using jQuery and JavaScript?

It's just a typo. Change:

$(this).foucus();

To:

$(this).focus();

Also, you might want to make it easier for your users to correct their mistake by also calling select on the textbox. That way, they can just begin typing again to change the value:

$(this).focus().select();

Here is a working example.


Note: This answer fixes the problem at hand, i.e. the question that was asked. On a broader scale, I do agree with the others who are saying that one shouldn't lock the user into a field. A better way of doing this would be to validate the whole form on submit, letting the users see all the problems and fixing them all at once, instead of bugging them throughout.


The event should be blur you're looking for. And your original jsfiddle had a typo (.foucus instead of focus)

And as a commenter said, visitors won't like this behavior.

http://jsfiddle.net/qdT8M/4/


$("#input").focus();


$("#input").blur(function() {
    setTimeout(function() { $("#input").focus(); }, 0);
});