1

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

5

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"
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

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).
1
var re = /entry\[(\d{1})\]/;
var index = re.exec(string);

Comments

0

You can do the trick using regular expressions.

Comments

0
var name  = $("#secondEntry").attr('name');
var index = name.substring( 6, name.length - 1 );

3 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.