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>
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:
type="textarea"
doesn't make sense as an attribute on an <input>
. If you want a textarea, use a <textarea>
.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>