Jonas
Jonas

Reputation: 128827

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

I have a textfield <input type="text"/> that I want to validate when the focus is lost. If the input is not valid, I want to prevent the focus moving to the next element, or in other words keep the focus at the invalid input until it's valid.

How can I do that using jQuery and JavaScript?

I have tried with this code, but it doesn't work (jsFiddle):

<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.6.2.min.js"></script>
<script>
$(function() {
    $('.hello').bind('focusout', function(e) {
        if(!isValid($(this).val())) {
            e.preventDefault();
            $(this).foucus();
        }
    });
});

    function isValid(str) {
        if(str === "hello") {
            return true;
        } else {
            return false;
        }
    }
</script>
</head>
<body>
Only valid content: <b>hello</b><br>
<input type="text" class="hello"/>
<button>Dummy</button>
</body>
</html>

Upvotes: 9

Views: 31411

Answers (4)

FishBasketGordo
FishBasketGordo

Reputation: 23142

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.

Upvotes: 10

Otto Kanellis
Otto Kanellis

Reputation: 3708

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


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

Upvotes: 4

Doozer Blake
Doozer Blake

Reputation: 7797

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/

Upvotes: 4

realshadow
realshadow

Reputation: 2585

Instead of $(this).focus(), use $(this).trigger('focus');. And the event should be blur, not focusout.

Edit: oh well, focus() will work as well :)

Upvotes: 0

Related Questions