index of an element inside a form

admin

Administrator
Staff member
Hi,<br />
<br />
suppose I have a form and all kinds of inputs inside of it.<br />
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)<br />
<br />
thanks in advance<!--content-->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:<br />
<br />
<script type="text/javascript"><br />
function getIndex() {<br />
tofind = "input2";<br />
x = 0;<br />
for (i=0; i<document.myform.elements.length; i++) {<br />
if (document.myform.elements.name == tofind) {<br />
arrayindex = i;<br />
x = 1;<br />
}<br />
}<br />
if (x == 1) {<br />
alert (arrayindex);<br />
}<br />
else {<br />
alert ("index not found");<br />
}<br />
}<br />
window.onload = getIndex;<br />
</script><br />
</head><br />
<body><br />
<form name="myform"><br />
<input type="text" name="input0"><br />
<input type="text" name="input1"><br />
<input type="text" name="input2"><br />
<input type="text" name="input3"><br />
<input type="text" name="input4"><br />
</form><!--content-->
 
Back
Top