views:

6391

answers:

3

How can you select an element that has current focus?

There is no :focus filter in jQuery, that is why we can use something like this:

$('input:focus').someFunction();
+5  A: 

Really the best way to do it is to setup a handler for the onFocus event, and then set a variable to the ID of the element that has focus.

something like this:

var id;

$(":input").focus(function () {
     id = this.id;
});
Mike_G
Why $(this).attr('id') use this.id
redsquare
Becareful because the window can also receive focus, which means this code won't work as expected in all cases.
cbp
+4  A: 

Have you tried

$.extend($.expr[':'], {
    focused: function(elem) { return elem.hasFocus; }
});

alert($('input :focused').length);
bendewey
`document.hasFocus()` does exist, but such a method or attribute is not available for elements. Tried in Firefox and Chromium.
akaihola
+5  A: 

alert($("*:focus").attr("id"));

I use jQuery.

It will alert id of element is focusing.

I hope it useful for you.

BiBi
Perfect answer!
kingjeffrey