Web Front-end
HTML Tutorial
Dynamically generate form elements with dynamic names using JavaScript
Dynamically generate form elements with dynamic names using JavaScript

This article aims to guide developers on how to use JavaScript to dynamically create input fields with incrementing names in forms. Through the `addCourse()` function and template strings, you can easily generate new course input boxes and ensure that the name of each input box contains a unique index, making it easier to process form data on the backend.
In web development, dynamically generating form elements is a common need, especially when users are required to enter multiple similar data items. This tutorial will demonstrate how to implement this functionality using JavaScript, focusing on dynamically generating form input boxes with incrementing names, such as courses[0][course_name], courses[1][no_of_students], etc.
Implementation steps
-
HTML structure preparation
First, a container element is needed to store the dynamically generated input box. A button is used to trigger the build action.
<div> <button type="button" class="btn btn-seconday" onclick="addCourse()">Add Course</button> <div id="course_add" class="container"> </div> </div>
Note: The course_add div is initially empty and we will add the new input box to it using JavaScript.
-
JavaScript function writing
Next, write a JavaScript function to dynamically generate HTML code and insert it into the container.
let index = 0; function addCourse() { const courseHtml = generateCourse(index); var mydiv = document.getElementById("course_add"); mydiv.insertAdjacentHTML('beforeend', courseHtml); } function generateCourse(indexValue) { return `<div class="form-group"> <label for="course name">Course Name</label> <input type="text" class="block rounded py-1 ml-4 text-sm" name="courses[${indexValue}][course_name]"> </div> <div class="form-group"> <label for="no_of_students">Number of Students</label> <input type="text" class="block rounded py-1 ml-4 text-sm" name="courses[${indexValue}][no_of_students]"> </div>` } //add the first course instead of using HTML directly addCourse()- index: This is a global variable used to track the number of input boxes that have been created and used to generate unique names.
- addCourse(): This function is called when the button is clicked. It calls the generateCourse() function to generate new HTML code, and then uses the insertAdjacentHTML() method to add the code to the course_add container.
- generateCourse(indexValue): This function accepts an index value and uses a template string to generate HTML code containing two input boxes (course name and number of students). The key is the name attribute, which uses ${indexValue} to insert the current index value, ensuring that each input box has a unique name.
- addCourse(): Automatically called once when the page loads to ensure that there is at least one course input box when the page loads.
-
Code explanation
- insertAdjacentHTML('beforeend', courseHtml): This method inserts courseHtml to the end of mydiv. The beforeend parameter means inserting HTML code after the last child node of the element.
- Template strings (backticks ``): Allow variables to be embedded in strings, making the code more readable and maintainable.
- index: After each call to addCourse(), the index variable will be incremented to ensure that each generated input box has a unique name.
Things to note
- Security: In real applications, it is important to validate and sanitize user input to prevent cross-site scripting attacks (XSS).
- Error handling: You can add error handling mechanisms, such as checking whether getElementById() returns null, and handling exceptions that may be thrown by insertAdjacentHTML().
- Styles: The class attribute is used in the sample code to apply styles. You can modify the style class name or use inline styles as needed.
- Initialization : It is recommended to add at least one set of input boxes when the page loads so that users can fill them in directly without having to click the "Add Course" button first.
Summarize
In this tutorial, you learned how to use JavaScript to dynamically generate form elements with incrementing names. This approach provides the flexibility to handle a variety of form needs, improves user experience, and simplifies back-end data processing. Remember, in real applications, it is important to pay attention to security, error handling, and code maintainability.
The above is the detailed content of Dynamically generate form elements with dynamic names using JavaScript. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20528
7
13637
4
Chart.js complete implementation solution for dynamically switching chart types (line chart, bar chart, pie chart)
Mar 12, 2026 pm 08:51 PM
This article explains in detail how to safely and reliably dynamically switch chart types (line/bar/pie) in Chart.js, and solve the problem of Cannot read properties of undefined errors caused by mismatched data structures and rendering exceptions after type switching. The core lies in destroying old instances, deep copying configurations, and accurately rebuilding data structures by type.
How to dynamically pass HTML form data to analytics.track() method
Mar 13, 2026 pm 10:57 PM
This article explains in detail how to safely and efficiently extract user input from HTML forms and structure it into JavaScript objects as attribute parameters of analytics.track() to avoid hard coding and syntax errors and support flexible expansion.
How to optimize Lighthouse image scoring while maintaining high image quality
Mar 11, 2026 pm 09:39 PM
This article explores why providing 2x images to high DPR devices may lower Lighthouse performance scores, and provides practical solutions to balance visual quality and real performance: including proper srcset configuration, image compression strategies, modern format selection, and load priority control.
A complete guide to using the keyboard to control the smooth movement of HTML elements
Mar 13, 2026 pm 10:18 PM
This article explains in detail why transform: translate() combined with the keydown event cannot move elements, and provides a reliable solution based on CSS positioning and JavaScript, covering absolute positioning settings, coordinate update logic, code robustness optimization, and common pitfalls.
How to properly override default styles and implement custom CSS layouts in Divi theme builder
Mar 14, 2026 am 12:00 AM
This article explains in detail the root cause of style failure when applying custom CSS in the WordPress Divi theme builder. It provides practical solutions for improving selector specificity, accurately positioning elements, and rational use of !important, as well as debugging tips and code optimization examples.
How to add prompt copy for disabled button click
Mar 30, 2026 pm 04:30 PM
This article introduces a complete solution for disabling the "Next" button when the form does not meet the conditions, and using native HTML5 form validation or JavaScript dynamic control to display a friendly prompt message when the disabled button is clicked.
How to switch images by clicking a button (elegant implementation based on jQuery)
Apr 04, 2026 pm 08:06 PM
This article introduces how to use jQuery to dynamically switch background images after button clicks, and corrects problems such as CSS selector misuse, inline event coupling, and logical redundancy in the original code, providing a concise and maintainable interaction solution.
How to use Python to quickly set up a local development server for mobile responsive testing
Apr 05, 2026 pm 08:06 PM
This article introduces how to use Python's built-in module to quickly start a lightweight HTTP server. You can access local projects in a mobile browser through the LAN without deployment, and realize real-time real-machine debugging of responsive designs.





