如何使用Javascript获取表单中文本字段数组的索引

How to get index of textfield array in the form by using Javascript?

本文关键字:字段 数组 索引 文本 中文 何使用 Javascript 获取 表单      更新时间:2023-09-26

我有一个包含十几个textfield元素的表单。其值的任何更改都应执行Javascript函数。到目前为止,我知道该怎么做,但我无法检测到触发函数的文本字段的索引。我尝试了一些我在这里看到的解决方案&但没有成功。

<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>

您可能不应该为所有输入提供相同的名称和id。

但是,您仍然可以查找父节点,然后迭代父节点的子节点,直到找到要检索其索引的节点。

试试这个getIndex()函数:

<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>

查看此Fiddle:http://jsfiddle.net/LkJxV/

编辑:已更正代码(再次)(thx@Felix)

这里的问题是索引不是元素的属性。根据上下文的不同,它可能有不同的索引,但您可以尝试试试类似的东西:

    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
    }