Skip to content
Advertisement

Detect which form input has focus using JavaScript or jQuery

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.

Advertisement

Answer

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

var selectedInput = null;
$(function() {
    $('input, textarea, select').focus(function() {
        selectedInput = this;
    }).blur(function(){
        selectedInput = null;
    });
});
Advertisement