JavaScript实现按钮点击添加最多12个带动态ID的重复Div组件
Alright, let's solve this problem where you need to add up to 12 identical div components (each containing input/select fields) with dynamically generated unique IDs every time a button is clicked. I'll use vanilla JavaScript for this since it's lightweight and fits right into your existing setup—no frameworks required.
Step 1: Tweak Your Base HTML
First, adjust your HTML to include an add button, and mark your inner div as a reusable template (we'll keep the first instance visible for consistency, or you can hide it if you want to start from zero):
<!-- Button to trigger adding new components --> <button id="btnAddRoute">Add New Route</button> <!-- Container where all components will live --> <div id="dvNPEAddData"> <!-- First visible component (base template) --> <div class="npe-component"> <label>Terminated route name</label> <input type="text" id="txtTerRouteName_0" /> <label>Cable Type</label> <select id="ddlCableType_0"> <option value="--Select--">--Select--</option> <option value="G652">G652</option> <option value="G655">G655</option> </select> </div> </div>
Note: I added a class npe-component to the inner div to make cloning easier, and gave the first instance IDs with a _0 suffix for consistent naming.
Step 2: Add the JavaScript Logic
Now drop this script in to handle the button click, clone the template, generate unique IDs, and enforce the 12-component limit:
// Initialize counter (starts at 1 since we already have the 0th component) let componentCounter = 1; const maxComponents = 12; // Grab references to key elements const addButton = document.getElementById('btnAddRoute'); const container = document.getElementById('dvNPEAddData'); const template = document.querySelector('.npe-component'); addButton.addEventListener('click', () => { // Stop if we hit the 12-component limit if (componentCounter >= maxComponents) { alert('You can add a maximum of 12 routes'); return; } // Clone the template div (true = deep clone, includes all child elements) const newComponent = template.cloneNode(true); // Update IDs for the new component's input and select const routeInput = newComponent.querySelector('input'); routeInput.id = `txtTerRouteName_${componentCounter}`; // Reset input value so it's empty for the new entry routeInput.value = ''; const cableSelect = newComponent.querySelector('select'); cableSelect.id = `ddlCableType_${componentCounter}`; // Reset select to the default "--Select--" option cableSelect.selectedIndex = 0; // Add the new component to the container container.appendChild(newComponent); // Increment counter for the next click componentCounter++; });
Key Details to Note
- Unique IDs: The counter suffix (
_0to_11) guarantees every input/select has a unique ID—no DOM conflicts! - Limit Enforcement: The script checks the counter before adding a new component and alerts users when they hit the 12-component cap.
- Clean State: Each new component resets input/select values to defaults, so users don't get pre-filled data from the template.
- Efficient Cloning: Cloning the existing div is faster and cleaner than building HTML from scratch every time.
If you want to start with no visible components (create the first one on click), just hide the template div with CSS (display: none;) and set componentCounter to 0 instead of 1.
内容的提问来源于stack exchange,提问作者Nadeem

