Detect which form input has focus using JavaScript or jQuery

focus, forms, javascript, jquery

Solution

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

Problem

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.

Original source