You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取动态追加表单行的元素值并推入对应数组

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 same item-row class.
  • 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 quantity to an integer and price to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 16:22:42