jQuery按键名计算多维数组:动态表单库存余量计算咨询
Solution for Dynamic Nested Array Input Calculations in JavaScript
Got it, let's work through this problem together. The main hurdle here is that your input fields use a nested array naming pattern generated dynamically by PHP—so we can't hardcode specific keys like FRUIT or YELLOW in our JavaScript. Instead, we need to dynamically parse input names to link each sell field to its matching stock and newstock counterparts.
Here's a flexible, scalable approach that works no matter what category/color keys PHP generates:
Step 1: Your Existing HTML (for reference)
<!-- Dynamically generated fields from PHP --> <input type=number name="sell['FRUIT']['YELLOW']" placeholder="Enter sell amount"> <input type=number name="stock['FRUIT']['YELLOW']" value=100 disabled> <input type=number name="newstock['FRUIT']['YELLOW']" disabled> <input type=number name="sell['WOOD']['BLACK']" placeholder="Enter sell amount"> <input type=number name="stock['WOOD']['BLACK']" value=50 disabled> <input type=number name="newstock['WOOD']['BLACK']" disabled> <input type=number name="sell['VEGETABLE']['RED']" placeholder="Enter sell amount"> <input type=number name="stock['VEGETABLE']['RED']" value=25 disabled> <input type=number name="newstock['VEGETABLE']['RED']" disabled> <input type=number name="sell['VEGETABLE']['GREEN']" placeholder="Enter sell amount"> <input type=number name="stock['VEGETABLE']['GREEN']" value=40 disabled> <input type=number name="newstock['VEGETABLE']['GREEN']" disabled>
Step 2: JavaScript Implementation
// Wait for the page to fully load before running code document.addEventListener('DOMContentLoaded', function() { // Grab all sell input fields using their name pattern const sellInputs = document.querySelectorAll('input[name^="sell["]'); // Core function to calculate and update newstock function updateNewstock(sellInput) { // Parse the sell input's name to extract category and color keys const namePattern = sellInput.name.match(/sell\['([^']+)'\]\['([^']+)'\]/); if (!namePattern) return; // Skip if the name format doesn't match our expected pattern const [_, category, color] = namePattern; // Find the corresponding stock and newstock inputs using the parsed keys const stockInput = document.querySelector(`input[name="stock['${category}']['${color}']"]`); const newstockInput = document.querySelector(`input[name="newstock['${category}']['${color}']"]`); if (!stockInput || !newstockInput) return; // Skip if matching fields can't be found // Handle empty or non-numeric inputs (default to 0 to avoid NaN) const stockValue = parseInt(stockInput.value) || 0; const sellValue = parseInt(sellInput.value) || 0; // Calculate and set the newstock value newstockInput.value = stockValue - sellValue; } // Attach event listeners to each sell input for real-time updates sellInputs.forEach(input => { input.addEventListener('input', () => updateNewstock(input)); // Run once on page load to initialize newstock values updateNewstock(input); }); });
Key Details About This Solution:
- Dynamic Name Parsing: The regular expression
/sell\['([^']+)'\]\['([^']+)'\]/pulls out the category and color keys from thesellinput's name. This works for any valid keys PHP generates, no hardcoding needed. - Real-Time Updates: Every time the user types or changes a
sellvalue, theinputevent triggers the calculation immediately. - Error Resilience: We default to
0for empty or non-numeric inputs to prevent weirdNaNvalues, and we skip processing if matchingstock/newstockfields aren't found. - Initialization: We run the calculation once when the page loads to make sure
newstockfields show the correct starting value (stock minus 0, since sell is empty by default).
This code scales seamlessly—you can add as many dynamically generated category/color pairs as you want, and the JavaScript will handle them automatically without any tweaks.
内容的提问来源于stack exchange,提问作者De Premor
相关产品推荐
相关产品推荐

