简体   繁体   中英

How do I append input node to form with JavaScript while keeping existing form data?

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM