0

I have a form with which a user can dynamically add text inputs. This generates a form with multiple text inputs that have the same name. If this form is submitted they overwrite each other. To solve this I need change the names so that they are appended with an incremented prefix when the form is submitted. Can anyone help?

Example of form (once three inputs have been added):

<form action="" method="post">
<td class="recipe-table__cell">
<input id="answer" name="the_answer" type="text" value="" >
<input id="answer" name="the_answer" type="text" value="" >
<input id="answer" name="the_answer" type="text" value="" >
</td>
<input type="submit" value="Submit">
</form>

Desired Post output on submission:

Array ( [1-answer] => test [2-answer] => ok [3-answer] => nice)

rather than Array ( [answer] => test )

1
  • You should not have more than one id per page, even before JavaScript. Commented Oct 13, 2017 at 3:43

1 Answer 1

1

First, select all of the elements that you want to add the attribute for. This can be done with .querySelectorAll().

Second, loop over those elements.

Third, use .setAttribute() to change the name attribute to append the index from the loop.

Note that you'll also want to increment the ID attribute, as you can't have duplicate IDs on the same page. You'll also want to swap your <td> elements for <div> elements to both allow .querySelectAll() to work correctly, and ensure valid markup.

This can be seen in the following example:

var inputs = document.querySelectorAll("form div input");
for (var i = 0; i < inputs.length; i++) {
  inputs[i].setAttribute("id", "answer" + i);
  inputs[i].setAttribute("name", "the_answer" + i);
  console.log(inputs[i]); // Added purely to show the change
}
<form action="" method="post">
  <div class="recipe-table__cell">
    <input id="answer" name="the_answer" type="text" value="">
    <input id="answer" name="the_answer" type="text" value="">
    <input id="answer" name="the_answer" type="text" value="">
  </div>
  <input type="submit" value="Submit">
</form>

Hope this helps! :)

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

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.