/    Sign up×
Community /Pin to ProfileBookmark

How can I determine if a particular form element has the focus at any given time? I do not want to add any event handlers to the form element. I just want to be able to read the form element’s focus ‘property’ (if such a thing exists) in my script.

to post a comment
JavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@CrazyC115Jun 04.2004 — [i]Originally posted by ssmith1000 [/i]

[B]How can I determine if a particular form element has the focus at any given time? I do not want to add any event handlers to the form element. I just want to be able to read the form element's focus 'property' (if such a thing exists) in my script. [/B][/QUOTE]


Best I could come up with is the following. An alert box will fire only if the element with the focus is a child element of "form1". I've only tested this in IE6 as well so it may not work properly with other browsers.

<i>
</i>&lt;html&gt;
&lt;head&gt;
&lt;script type="text/javascript"&gt;
function testFocus()
{
var oSource = event.srcElement;

<i> </i> if (oSource.parentNode.name == "form1")
<i> </i> {
<i> </i> alert(oSource.name);
<i> </i> }
<i> </i> }

<i> </i> document.onactivate = testFocus;
<i> </i> &lt;/script&gt;
<i> </i>&lt;/head&gt;
&lt;body&gt;

<i> </i>&lt;form name="form1"&gt;
<i> </i> &lt;input type="text" name="text1" value=""&gt;&lt;br&gt;
<i> </i> &lt;input type="text" name="text2" value=""&gt;&lt;br&gt;
<i> </i> &lt;input type="button" name="button1" value="a button"&gt;&lt;br&gt;
<i> </i> &lt;input type="checkbox" name="checkbox1"&gt;&lt;br&gt;
<i> </i> &lt;select name="select1"&gt;
<i> </i> &lt;option value="-1"&gt;-Select One-&lt;/option&gt;
<i> </i> &lt;/select&gt;
<i> </i>&lt;/form&gt;

<i> </i>&lt;form name="form2"&gt;
<i> </i> &lt;input type="text" name="text3" value=""&gt;&lt;br&gt;
<i> </i> &lt;input type="text" name="text4" value=""&gt;&lt;br&gt;
<i> </i> &lt;input type="button" name="button2" value="a button"&gt;&lt;br&gt;
<i> </i> &lt;input type="checkbox" name="checkbox2"&gt;&lt;br&gt;
<i> </i> &lt;select name="select2"&gt;
<i> </i> &lt;option value="-1"&gt;-Select One-&lt;/option&gt;
<i> </i> &lt;/select&gt;
<i> </i>&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
×

Success!

Help @ssmith1000 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.2,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,
)...