如何基于数组长度与元素名称生成动态表单?
Solution: Generate Input Fields from Array Elements
Got it, let's tweak that script to match your exact requirement—we'll ditch the user-input number and instead use your predefined array to create input fields, each named after the array's elements. Here's the updated working code:
<html> <head> <script type='text/javascript'> function addFields(){ // Your predefined array of field names const fieldNames = ['loren', 'ipsum', 'plumpus', 'dumbas']; // Container where dynamic content will be placed const container = document.getElementById("container"); // Clear previous contents of the container while (container.hasChildNodes()) { container.removeChild(container.lastChild); } // Loop through the array to create fields for (let i = 0; i < fieldNames.length; i++){ // Append the field name as label text container.appendChild(document.createTextNode(fieldNames[i])); // Create input element const input = document.createElement("input"); input.type = "text"; // Set input name to the corresponding array element input.name = fieldNames[i]; container.appendChild(input); // Add line break container.appendChild(document.createElement("br")); } } </script> </head> <body> <!-- No need for the number input anymore --> <a href="#" id="filldetails" onclick="addFields()">Fill Details</a> <div id="container"></div> </body> </html>
Key Changes Explained:
- Predefined Array: We added
const fieldNames = ['loren', 'ipsum', 'plumpus', 'dumbas'];to hold your target field names (note: I added quotes around each string—missing those would cause JavaScript errors!) - Array-Driven Loop: Instead of using
document.getElementById("member").value, we loop usingfieldNames.lengthto match the array's size exactly - Field Naming: Each input's
nameattribute is set directly to the array element at the current index (input.name = fieldNames[i]), and we also display the element name as the label text instead of generic "Member X" - Cleaned Up UI: Removed the number input since we no longer need user input to determine the number of fields
Just click the "Fill Details" link, and it'll generate 4 input fields named after your array elements, every time!
内容的提问来源于stack exchange,提问作者W.Lyman
相关产品推荐
相关产品推荐

