Home >Web Front-end >JS Tutorial >How to Dynamically Generate Input Form Elements in JavaScript?
This article delves into a common programming challenge: dynamically creating input form elements based on user input. The goal is to provide a clear and straightforward solution for beginners, using JavaScript.
A web page includes a text input field where users can enter a number. Upon clicking a corresponding link, the page should dynamically generate that many input fields for the user to provide additional information. Users can enter a maximum of 10 values.
Retrieving User Input:
Creating the Container:
Generating Elements Dynamically:
Clearing Previous Elements:
Additional Enhancements:
The following code snippet demonstrates the implementation of the solution:
<html> <head> <script type='text/javascript'> function addFields(){ // Get number of inputs var number = document.getElementById("member").value; // Get container var container = document.getElementById("container"); // Clear container while (container.hasChildNodes()) { container.removeChild(container.lastChild); } // Generate inputs for (i=0;i<number;i++){ // Text node container.appendChild(document.createTextNode("Member " + (i+1))); // Input element var input = document.createElement("input"); input.type = "text"; input.name = "member" + i; container.appendChild(input); // Line break container.appendChild(document.createElement("br")); } } </script> </head> <body> <input type="text" id="member" name="member" value="">Number of members: (max. 10)<br /> <a href="#" id="filldetails" onclick="addFields()">Fill Details</a> <div id="container"/> </body> </html>
The above is the detailed content of How to Dynamically Generate Input Form Elements in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!