user558134
user558134

Reputation: 1129

Jquery how to get index from input name attribute

I have this code which works ok, but i was wondering if it could be done faster with jquery to get the index from input name attribute

<input name="inp[myindex]" value="bla" />

and the jquery

var $idx = $this.attr('name');
var $split = $idx.split('[');
$idx = $split[1];
$idx = $idx.replace(']', '');

Thanks in advance!

Upvotes: 3

Views: 3332

Answers (3)

bobince
bobince

Reputation: 536429

A concise idiom to extract a string between two boundaries is split-pop-shift:

var subname= this.name.split('[').pop().split(']').shift();

or there's always the regex method, shorter still though ugly:

var subname= this.name.match(/\[([^[]*)\]/)[1];

jQuery is focused on DOM manipulations and doesn't have its own string processing functions to speak of. The method of using square brackets for indexed field names is a PHP quirk rather than anything inherent to HTML, which sees names only as plain old strings.

Upvotes: 7

systemizer
systemizer

Reputation: 355

 $('input[name="<name-here>"]')

Upvotes: -2

James Montagne
James Montagne

Reputation: 78650

There are other ways to do this, but nothing with jquery. Just other variations of substring, replace, etc.

Upvotes: 0

Related Questions