Gaining control over the textfield in focus...

This topic is 4730 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

Hey everyone, is there a way to know in javascript what field the user is currently in? Sorry for such a newb question but I've never looked into somthing like that before. Thanks in advance.

Share on other sites
As far as I'm personally aware, there is no standard way to query an element to see if it has focus - I've never had the need to find out. One thing you might try is to handle the onfocus() and onblur() events for the elements you're interested in, and set a variable that tracks the currently focused element (if any). Be warned, though, that it is possible that you may incorrectly track an element as having focus even if the OS focus has moved to another window. In general this solution is a bit ugly.

What are you needing to accomplish? Perhaps there's a cleaner way to do it?

Share on other sites
Thank you for your help so far, all I need to do is find out which textbox they're in so I can figure out which one they're tpying in so I can insert stuff into the right box without making serperate controls for every box. Thanks in advance.

Share on other sites
In that case tracking the active control with onfocus() and onblur() is probably your best bet. You can just set up two functions HandleFocus() and HandleBlur() that have a parameter for the element that fired the event. Each element can be set up with onfocus="HandleFocus(this);" and that should take care of it.

<script>var ActiveElement = null;function HandleFocus(element){     ActiveElement = element;}function HandleBlur(element){     ActiveElement = null;}// The rest of your code here</script>

Just be sure to check for null anywhere you use the ActiveElement parameter and you should be set.

• 16
• 9
• 13
• 41
• 15