Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 721
Jonas Avatar asked Oct 02 '11 12:10

Jonas


2 Answers

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.

like image 104
FishBasketGordo Avatar answered Sep 22 '22 03:09

FishBasketGordo


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/

like image 33
Doozer Blake Avatar answered Sep 23 '22 03:09

Doozer Blake