1

If I have multiple html inputs all with an equal amount of array keys, but the keys are unknown, how can I get the value of the 3rd array key?

Example:

HTML

<input name="data[key1][key2][0]" />
<input name="data[key1][key2][1]" /> 
<input name="data[key1][key2][2]" />

What i'm looking for is the value of the 3rd key regardless of [key1][key2]. I need to get the value so I can reset indexes if an input is removed by the user.

So if a user removes the second input, the array is

<input name="data[key1][key2][0]" /> 
<input name="data[key1][key2][2]" />

I'd like to loop through the array and reset the indexes.

Any suggestions?

2 Answers 2

4

If you're just going to reset the index, you don't even need to get that number (demo)

$('input').each(function(i) {
    this.name = this.name.replace(/\[\d+\]$/, '[' + i + ']');
    console.log(this.name);
});
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for avoiding $(this).attr('name', ...) and using a vastly more efficient alternative that is also less to type. :-)
1

Slice the .name from the last [ to the last character.

this.name.slice(this.name.lastIndexOf("["), -1);

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.