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" wh开发者_如何学运维en 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]).
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"
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];
var re = /entry\[(\d{1})\]/;
var index = re.exec(string);
You can do the trick using regular expressions.
var name = $("#secondEntry").attr('name');
var index = name.substring( 6, name.length - 1 );
精彩评论