views:

72

answers:

2

I want a text field to always be focused. When they click out of the textfield, I want the focus to go back into the textfield.

How would I accomplish this with jquery?

$('input').focus();

$('input').**unfocused?**( function($) { $('input').focus();} );
+1  A: 

You're looking for the blur event:

$(':text').blur(function() { this.focus(); });
SLaks
`$("input").blur(function(){ $("input").focus(); });` does not work
twodayslate
@Slaks He's right... it should, but it doesn't. http://jsfiddle.net/pUFAV/
Yi Jiang
A: 

The following code is an alternative solution which depends on periodically checking the control's state.

var controlFocus=false;
$("#txtName").focus(function(){
    $(this).addClass("focused"); 
    if(!controlFocus) {
        controlFocus = true;
        setInterval(function(){ 
            var o = $("#txtName");
            if(!o.hasClass("focused")) o.focus();
        }), 200);
    }
}).blur(function(){$(this).removeClass("focused");});

After the textbox (named txtName) gets its first focus, every 0.2 second, the code controls whether the textbox has focus. If it doesn't, it's focused. But this can be a really annoying thing.

Zafer
I understand the idea but the script gives me errors. Also, wont this build up and make the site really slow?
twodayslate
What's the error? In fact I tried it on Jsfiddle with Chrome. You can increment the interval to 500 or 1000.
Zafer
From error console: Error: missing ; before statementSource Code: }), 200);
twodayslate