Home Articles FAQs XREF Games Software Instant Books About Feedback Search Site-Map
irt.org logo

Q964 How can I get the index of the element focused in the form?

irt.org | Knowledge Base | JavaScript | Form 2 | Q964 [ previous next ]

Q964 How can I get the index of the element focused in the form?

Unless you capture it at the time using onFocus, then you can't, as there isn't a focused property for form elements.

When the form element gains focus:

<script language="JavaScript"><!--
function getIndex(what,which) {
    for (var i=0;i < what.elements.length;i++)
        if (what.elements[i].name == which)
            return i;
    return -1;
}
//--></script>

<form>
<input type="text" name="text1" onFocus="document.otherForm.answer.value = 'index is ' + getIndex(this.form,this.name)">
<input type="text" name="text2" onFocus="document.otherForm.answer.value = 'index is ' + getIndex(this.form,this.name)">
<input type="text" name="text3" onFocus="document.otherForm.answer.value = 'index is ' + getIndex(this.form,this.name)">
</form>

<form name="otherForm">
<input type="text" name="answer">
</form>

The second form is for demonstration purposes only. Using an alert will constantly trigger the onFocus and onBlur events.


Provide feedback ...
AddThis Social Bookmark Button

Provide feedback ... AddThis Social Bookmark Button


Last Updated: 30th March 2008. Maintained by: Martin Webb and Michel Plungjan
irt.org liability, trademark, document use, privacy statement and software licensing rules apply.
Copyright © 1996-2008 irt.org, All Rights Reserved.