Saket Bisht
Saket Bisht

Reputation: 37

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

I have some input fields, having same names but I only want to get the value of index of each input like this

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

So, for example I only wants to get 20, 2, 14 from op_price name attribute, is their any JS or jquery method to do this

Upvotes: 1

Views: 2388

Answers (5)

Rituraj ratan
Rituraj ratan

Reputation: 10378

like if you get your name property

   var name="op_price[20]"  

name.replace(/op_price\[(\d*)?]/gi, $1);

then op_price[20] replace with 20

Upvotes: 0

Arvind Bhardwaj
Arvind Bhardwaj

Reputation: 5291

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

See DEMO

Upvotes: 0

Sayed
Sayed

Reputation: 631

if you're not going to change the name of your input fields, may be you can iterate through a loop to get all the values? Try this:

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

this will give you the value of the ith input field in each iteration of the loop!

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 121998

Use attributeContains selector

Ex from docs :

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

Upvotes: 0

omma2289
omma2289

Reputation: 54619

This will return the indexes in an array:

var indexes = $('[name^="op_price"]').map(function(){
    return this.name.match(/\d+/);
}).get();

console.log(indexes); // ["20", "2", "14"] 

Upvotes: 5

Related Questions