如何获取动态追加表单行的元素值并推入对应数组
Solution to Collect Dynamic Form Row Values
Hey there! Let's get your Save Sales functionality working properly. Here's a straightforward solution to collect all the row values into your items[], quantities[], and prices[] arrays when the button is clicked:
Step 1: Ensure Your HTML Structure is Set Up Correctly
First, make sure all your dynamic rows are wrapped in a container, and each input has a consistent class so we can target them easily. Here's an example structure:
<!-- Container for all item rows --> <div class="items-container"> <!-- Initial row --> <div class="form-group form-row item-row"> <input type="text" class="item-input" placeholder="Item Name"> <input type="number" class="quantity-input" placeholder="Quantity" min="1"> <input type="number" class="price-input" placeholder="Price" min="0.01" step="0.01"> </div> </div> <button id="addRowBtn">Add</button> <button id="saveSalesBtn">Save Sales</button> <!-- Optional customer info fields --> <input type="text" id="customerName" placeholder="Customer Name"> <!-- Add other customer fields as needed -->
Step 2: Implement the JavaScript Logic
We'll handle both adding new rows and collecting the data on save. Here's the full code:
// Your existing variables let CustomerName; let CustomerAddress; let CustomerNumber; let CustomerType; let itemsNumber = 1; let items = []; let quantities = []; let prices = []; let timeNdate; // Add new row functionality document.getElementById('addRowBtn').addEventListener('click', function() { const container = document.querySelector('.items-container'); const newRow = document.createElement('div'); newRow.className = 'form-group form-row item-row'; newRow.innerHTML = ` <input type="text" class="item-input" placeholder="Item Name"> <input type="number" class="quantity-input" placeholder="Quantity" min="1"> <input type="number" class="price-input" placeholder="Price" min="0.01" step="0.01"> `; container.appendChild(newRow); itemsNumber++; }); // Save Sales functionality document.getElementById('saveSalesBtn').addEventListener('click', function() { // Reset arrays to avoid duplicate data from previous saves items = []; quantities = []; prices = []; // Get all item rows (initial + dynamically added) const allRows = document.querySelectorAll('.item-row'); let isFormValid = true; allRows.forEach(row => { // Extract values from each input in the row const item = row.querySelector('.item-input').value.trim(); const quantity = row.querySelector('.quantity-input').value; const price = row.querySelector('.price-input').value; // Basic validation: ensure all fields are filled if (!item || !quantity || !price) { alert('Please fill out all fields in every item row!'); isFormValid = false; return; // Exit the loop if invalid } // Push values to arrays (convert quantity/price to numbers) items.push(item); quantities.push(parseInt(quantity)); prices.push(parseFloat(price)); }); if (!isFormValid) return; // Collect other customer data (adjust selectors to match your HTML) CustomerName = document.getElementById('customerName').value.trim(); // CustomerAddress = document.getElementById('customerAddress').value.trim(); // ... add other customer fields here // Set timestamp timeNdate = new Date().toLocaleString(); // Or use toISOString() for UTC format // Optional: Log data to verify it's working console.log('Items:', items); console.log('Quantities:', quantities); console.log('Prices:', prices); console.log('Customer Name:', CustomerName); console.log('Timestamp:', timeNdate); // Add your code to submit this data to a server here });
Key Notes:
- Targeting Rows: We use
document.querySelectorAll('.item-row')to grab all rows (initial and dynamic) — this works because every new row gets the sameitem-rowclass. - Reset Arrays: We clear the arrays before each save to prevent old data from sticking around if the user saves multiple times.
- Data Type Conversion: We convert
quantityto an integer andpriceto a float, since input values are always strings by default. This is important if you plan to do calculations later. - Basic Validation: The code checks that all fields are filled before collecting data — you can expand this validation (e.g., check for positive numbers) if needed.
内容的提问来源于stack exchange,提问作者Sohel Shekh
相关产品推荐
相关产品推荐

