简体   繁体   中英

How to access element by index name by Jquery?

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]).

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

您可以使用正则表达式来解决问题

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM