如何从多个元素的相同名称中获取名称属性的索引

How to get index of name attribute from same name of multiple elements.

本文关键字:获取 索引 属性 元素      更新时间:2023-09-26

我有一些输入字段,名称相同,但我只想像这个一样获得每个输入的索引值

<input type="text" name="op_price[20]" value="20.00" size="3"  >
<input type="text" name="op_price[2]" value="13" size="3">
<input type="text" name="op_price[14]" value="12" size="3">

因此,例如,我只想从op_price name属性中获得20、2、14,这是他们的任何JS或jquery方法来完成

这将返回数组中的索引:

var indexes = $('[name^="op_price"]').map(function(){
    return this.name.match(/'d+/);
}).get();
console.log(indexes); // ["20", "2", "14"] 

使用属性包含选择器

来自文档的Ex:

$( "input[name*='man']" ).val();

如果您不打算更改输入字段的名称,那么您可以通过循环迭代来获得所有值吗?试试这个:

for(i=0;document.getElementById('op_price['+i+']';i++)
 alert(document.getElementById('op_price['+i+']');

这将在循环的每次迭代中为您提供第i个输入字段的值!

var name = $("input:text").attr("name");
name = name.replace("op_price[", "").replace("]", "");
alert(name);

请参阅DEMO

如果你得到你的名字属性

   var name="op_price[20]"  
name.replace(/op_price'[('d*)?]/gi, $1);

则op_price[20]替换为20