2

I would like to add another input field into the form each time I click the button in the code below. Using appendChild(), it seems as though I can only do this one time. I tried adding the field using innerHTML, but this removes what has already been typed in the existing form fields. What would be the best way to achieve this with vanilla JavaScript while keeping what has already been typed into the form? Thank you in advance for your help.

let getArticleForm = document.getElementById("articleForm");
let cloneInputNode = document.getElementById("textInput").cloneNode(true);
cloneInputNode.setAttribute("id", "newId");

function addInput() {
  getArticleForm.appendChild(cloneInputNode);
}
<form id ='articleForm'>
  <input id="textInput" type="textarea"></input>
</form>
<button onClick="addInput()">add input</button>

Codepen

1 Answer 1

1

Clone it inside the listener, else you've only created one clone (which gets removed from its prior location when appended again).

let getArticleForm = document.getElementById("articleForm");

function addInput() {
  getArticleForm.appendChild(document.getElementById("textInput").cloneNode(true));
}
<form id ='articleForm'>
  <input id="textInput" type="textarea"></input>
</form>
<button onClick="addInput()">add input</button>

But there are some other fixes to make too:

  • The cloned nodes will all have the same ID, which is invalid HTML. While you could set a new ID for each input, dynamic IDs are an antipattern anyway - better to leave it off entirely IMO.
  • type="textarea" doesn't make sense as an attribute on an <input>. If you want a textarea, use a <textarea>.
  • Instead of cloning the existing input, consider just appending a new input.

const getArticleForm = document.getElementById("articleForm");

function addInput() {
  getArticleForm.appendChild(document.createElement('input'));
}
<form id ='articleForm'>
  <input id="textInput" type="textarea"></input>
</form>
<button onClick="addInput()">add input</button>

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

2 Comments

Thank you, this helped me tremendously. Is there a way to accomplish this without copying the text that has already been typed in the original input field? So that the cloned node has no text input even if the original node already has text input.
Instead of cloning, I'd create an entirely new <input> instead, see snippet

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.