3

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!

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

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

Comments

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.