faqts : Computers : Programming : Languages : JavaScript : Forms

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

45 of 53 people (85%) answered Yes
Recently 6 of 10 people (60%) answered Yes

Entry

How can I find the index of a FORM element in the elements array?

Mar 2nd, 2000 20:02
Martin Honnen,


Sometimes you might to find the index of a form field you know by its 
name in the FORM's elements array. The following provides a function
  getFormIndex 
taking as the first argument a FORM object or a FORM name and as the 
second argument the field name. It returns the index in the elements 
array if the field is found or otherwise -1. An example form examining 
itself is included.

<HTML>
<HEAD>
<SCRIPT>
function getFormIndex (form, fieldName) {
  form = typeof form == 'string' ? document[form] : form;
  var found = false;
  for (var i = 0; i < form.elements.length; i++)
    if ((found = form.elements[i].name == fieldName))
      break;
  return found ? i : -1;
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="aForm">
<INPUT TYPE="text" NAME="fieldName">
<INPUT TYPE="button" VALUE="get index" NAME="aButton"
       ONCLICK="this.form.index.value = getFormIndex(this.form, 
this.form.fieldName.value)">
<BR>
<INPUT TYPE="text" NAME="index" SIZE="4">
</FORM>
</BODY>
</HTML>