views:

70

answers:

5

I have several INPUTs:

<input type="text" name="entry[1]" value="aaa" id="firstEntry" />
<input type="text" name="entry[2]" value="bbb" id="secondEntry" />
<input type="text" name="entry[3]" value="ccc" id="thirdEntry" />

How to get "2" when I know that element id is "secondEntry"?

var name = $("#secondEntry").attr('name'); // name = "entry[2]"

But how to get the index 2 ? I need to know just index (2), not whole name (entry[2]).

+5  A: 

Well the name is just a string, and you'd have to do the rest with string manipulation:

var name = $("#secondEntry").attr('name'); // name = "entry[2]"
name = name.substring(name.indexOf('[')+1); // name = "2]"

// if you want an integer
name = parseInt(name, 10); // name = 2

// if you want a string representation
name = name.substring(0, name.indexOf(']'));  // name = "2"
David Hedlund
A: 

You can do the trick using regular expressions.

Darmen
+1  A: 

If it is always in that format, ie entry[x], then you could use regular expressions;

var elename = $("#secondEntry").attr('name');
var i = elename.match("entry\\[([0-9])+\\]");
var ind = i[1];
Psytronic
And if you want it as a number, `var ind = parseInt(i[1])`. But drop "entry" from the regex so it's not fragile (doesn't break on name changes).
T.J. Crowder
A: 
var name  = $("#secondEntry").attr('name');
var index = name.substring( 6, name.length - 1 );
poke
Granted that works for his sample data, but *wow* is it fragile. Breaks if he changes `entry` to `item` at some point, or if there are more than nine, or...
T.J. Crowder
Of course it only works for "entry", but that is what he is looking at (and the RegExp solutions are not more general either); and regarding your second argument: `'entry[12413525]'.substring( 6, 'entry[12413525]'.length - 1 )` gives me `"12413525"`.
poke
@poke: Re the first item: Yeah, well, I commented on the other one I read too. Re second item: Doh! I just totally misread the length bit.
T.J. Crowder
+1  A: 
var re = /entry\[(\d{1})\]/;
var index = re.exec(string);
iburlakov