开发者

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 ne开发者_运维百科xt 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>


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);
});


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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜