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>
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Ludus H
  • 239
  • 2
  • 15

2 Answers2

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)

corentin
  • 679
  • 1
  • 6
  • 17
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
    }
raam86
  • 6,785
  • 2
  • 31
  • 46
  • 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 – Ludus H Jun 30 '13 at 16:46
  • @LudusH Nice to know . I corrected answer to reflect solution – raam86 Jun 30 '13 at 17:35