Everett Toews
Everett Toews

Reputation: 10956

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.

Upvotes: 32

Views: 45992

Answers (9)

Ruan Mendes
Ruan Mendes

Reputation: 92274

document.activeElement, it's been supported in IE for a long time and the latest versions of FF and chrome support it also. If nothing has focus, it returns the document.body object.

Upvotes: 62

Kevin Cohen
Kevin Cohen

Reputation: 1341

You can use this

<input type="text" onfocus="myFunction()">

It triggers the function when the input is focused.

Upvotes: 0

user2211815
user2211815

Reputation: 1

You only need one listener if you use event bubbling (and bind it to the document); one per form is reasonable, though:

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

(Maybe you should move the selectedInput variable to the form.)

Upvotes: 0

Vivek Viswanathan
Vivek Viswanathan

Reputation: 1

Try

window.getSelection().getRangeAt(0).startContainer

Upvotes: -1

Paolo Bergantino
Paolo Bergantino

Reputation: 488424

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

Upvotes: 17

Magnitus
Magnitus

Reputation: 378

Here's a solution for text/password/textarea (not sure if I forgot others that can get focus, but they could be easily added by modifying the if clauses... an improvement could be made on the design by putting the if's body in it's own function to determine suitable inputs that can get focus).

Assuming that you can rely on the user sporting a browser that is not pre-historic (http://www.caniuse.com/#feat=dataset):

        <script>
        //The selector to get the text/password/textarea input that has focus is: jQuery('[data-selected=true]')
        jQuery(document).ready(function() {
            jQuery('body').bind({'focusin': function(Event){
                var Target = jQuery(Event.target);
                if(Target.is(':text')||Target.is(':password')||Target.is('textarea'))
                {
                    Target.attr('data-selected', 'true');
                }
            }, 'focusout': function(Event){
                var Target = jQuery(Event.target);
                if(Target.is(':text')||Target.is(':password')||Target.is('textarea'))
                {
                    Target.attr('data-selected', 'false');
                }
            }});
        });
    </script>

For pre-historic browsers, you can use the uglier:

        <script>
        //The selector to get the text/password/textarea input that has focus is: jQuery('[name='+jQuery('body').data('Selected_input')+']')
        jQuery(document).ready(function() {
            jQuery('body').bind({'focusin': function(Event){
                var Target = jQuery(Event.target);
                if(Target.is(':text')||Target.is(':password')||target.is('textarea'))
                {
                    jQuery('body').data('Selected_input', Target.attr('name'));
                }
            }, 'focusout': function(Event){
                var Target = jQuery(Event.target);
                if(Target.is(':text')||Target.is(':password')||target.is('textarea'))
                {
                    jQuery('body').data('Selected_input', null);
                }
            }});
        });
    </script>

Upvotes: 1

vapcguy
vapcguy

Reputation: 7537

I would do it this way: I used a function that would return a 1 if the ID of the element it was sent was one that would trigger my event, and all others would return a 0, and the "if" statement would then just fall-through and not do anything:

function getSender(field) {
    switch (field.id) {
        case "someID":
        case "someOtherID":
            return 1;
        break;
        default:
            return 0;
    }
}

function doSomething(elem) {
    if (getSender(elem) == 1) {
       // do your stuff
    }
  /*  else {
       // do something else
    }  */
}

HTML Markup:

<input id="someID" onfocus="doSomething(this)" />
<input id="someOtherID" onfocus="doSomething(this)" />
<input id="someOtherGodForsakenID" onfocus="doSomething(this)" />

The first two will do the event in doSomething, the last one won't (or will do the else clause if uncommented).

-Tom

Upvotes: 1

Maxime Kjaer
Maxime Kjaer

Reputation: 782

Otherwise, you could use the onfocus and onblur events.

something like:

<input type="text" onfocus="txtfocus=1" onblur="txtfocus=0" />

and then have something like this in your javascript

if (txtfocus==1)
{
//Whatever code you want to run
}

if (txtfocus==0)
{
//Something else here
}

But that would just be my way of doing it, and it might not be extremely practical if you have, say 10 inputs :)

Upvotes: 2

Marc Novakowski
Marc Novakowski

Reputation: 45398

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.

Upvotes: 3

Related Questions