views:

7905

answers:

2

Hi,

How do you detect which form input has focus using JavaScript or jQuery?

From within a function I want to be able to determine which form input has focus. I'd like to be able to do this in straight JavaScript and/or jQuery.

Thanks, Everett

+2  A: 

If all you want to do is change the CSS for a particular form field when it gets focus, you could use the CSS ":focus" selector. For compatibility with IE6 which doesn't support this, you could use the IE7 library.

Marc Novakowski
`$('#some_id_here input[type=text]:focus')` will work for text inputs.
Matt Ball
This doesn't work at all for me - is there a new ":focus" selector?
Herb Caudill
I'm talking about a CSS selector, not a jQuery selector.
Marc Novakowski
This doesn't work on IE older version. I got an error
Cyril Gupta
+6  A: 

I am not sure if this is the most efficient way, but you could try:

var selectedInput = null;
$(document).ready(function() {
    $('input, textarea, select').focus(function() {
        selectedInput = this;
    });
});
Paolo Bergantino