0

I have a form with dozen of textfield elements. Any change of their values shall execute Javascript function. And until now I know what I shall to do, but I can't detect index of textfield that triggered function. I tried some solution I saw here & there but wasn't successful.

<form action="" method="post" enctype="multipart/form-data" name="myforma1" target="_self" id="myforma1"> <input name="txtfield" type="text" id="txtfield" onchange="detect_it(this);" value="name of person" size="20" maxlength="25" /> <input name="txtfield" type="text" id="txtfield" onchange="detect_it(this);" value="name of person" size="20" maxlength="25" /> <input name="txtfield" type="text" id="txtfield" onchange="detect_it(this);" value="name of person" size="20" maxlength="25" /> 

...

<script> function detect_it(oo) { alert('Index of triggered element is: ' + oo.index); /* rest of code */ } </script> 
0

2 Answers 2

1

You probably shouldn't give all your inputs the same name and id.

However, you can still look for the parent node, then iterate over the parent's children until you found your node to retrieve its index.

Try this getIndex() function:

<script> var getIndex = function (node) { for (var i =0;i<node.parentNode.children.length;i++) { if (node.parentNode.children[i] === node) { return i; } } } function detect_it(oo) { alert('Index of triggered element is: ' + getIndex(oo)); } </script> 

See this Fiddle: http://jsfiddle.net/LkJxV/

edit: corrected code (again) (thx @Felix)

Sign up to request clarification or add additional context in comments.

6 Comments

This will never return true since one element is input and the other is form
@raam86 I corrected my snippet
tried but got an error
Seems still not work. Add a working fiddle.
node.parentNode.length is incorrect.
|
0

Your problem here is that index is not a property of the element. It can have differnet indexes depending on context but you can try Try something like:

 function detect_it(oo){ var inputs = document.getElementsByTagName('input') for (var i = 0 ; i<inputs.length ; i++){ if(oo == inputs[i]{ alert('Index of triggered element is: ' + i); } } //enter code here } 

2 Comments

Thanks raam86, your code seems like solution I wanted. Just small error was there, I corrected it and it now works in Chrome and FF. function detect_it(oo){ var inputs = document.getElementsByName('txtfield') for (var i = 0 ; i<inputs.length ; i++){ if(oo == inputs[i]){ alert('Index of triggered element is: ' + i); } } } /* end */
@LudusH Nice to know . I corrected answer to reflect solution

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.