Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

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

You are here: irt.org | FAQ | JavaScript | Form | 2 | Q964 [ previous next ]

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.

©2018 Martin Webb