Click to See Complete Forum and Search --> : index of an element inside a form


chuvak
08-01-2003, 08:00 PM
Hi,

suppose I have a form and all kinds of inputs inside of it.
If I have a name of a for ex. text field inside the form, is there a way to find out it's index in the form's elements[] array? (besides, of course, just going through whole array until stumble on this name)

thanks in advance

pyro
08-01-2003, 11:45 PM
Not sure if you conside a for loop "going through the array until you stumble on it" but this is how I'd do it:

<script type="text/javascript">
function getIndex() {
tofind = "input2";
x = 0;
for (i=0; i<document.myform.elements.length; i++) {
if (document.myform.elements[i].name == tofind) {
arrayindex = i;
x = 1;
}
}
if (x == 1) {
alert (arrayindex);
}
else {
alert ("index not found");
}
}
window.onload = getIndex;
</script>
</head>
<body>
<form name="myform">
<input type="text" name="input0">
<input type="text" name="input1">
<input type="text" name="input2">
<input type="text" name="input3">
<input type="text" name="input4">
</form>