0

I'm trying to replace the [2] in the name values of the hidden fields with a new value within a loop. The 2 could be any number and so I won't necessarily know it when I'm looping. What would be the best course of action in replacing it?

<input type="hidden" class="pid" name="t[2][p][149][id]" value="ID">
<input type="hidden" class="pane" name="t[2][p][149][name]" value="NAME">

2 Answers 2

2
$("input").each(function() {
  name = $(this).attr("name");
  name = name.replace(/^t\[\d+\]/, "t[your number]");
  $(this).attr("name", name);
});
Sign up to request clarification or add additional context in comments.

3 Comments

From the question: "The 2 could be any number and so I won't necessarily know it when I'm looping."
Cool. Would also recommend not assuming all names should be processed... :-)
Still, won't work when the 'any number' has more than a single digit.
1

If it will always be the patten "t[number][..." you should create a regular expression and replace it that way.

2 Comments

Note that he asked for "the best course of action in replacing it" not "tell me exactly how to write the code to replace it" !
Yes. But, no reason not to go above and beyond. Plus, it's much easier to work out the english from the code, than the reverse.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.