如何获取动态行数表格receiptTable内所有input元素的取值?
Hey there, I’ve dealt with dynamic table input value extraction plenty of times—let’s get this sorted for you!
Solution 1: Vanilla JavaScript (No Libraries)
Since your table rows are dynamic, we don’t want to rely on hardcoding row counts. Instead, we’ll target all <input> elements directly inside the receiptTable and extract their values:
// Grab the table element first const receiptTable = document.getElementById('receiptTable'); // Select all input elements within the table const allInputs = receiptTable.querySelectorAll('input'); // Collect all input values into an array const inputValues = []; allInputs.forEach(input => { inputValues.push(input.value); // Optional: If you need to tie values to their parent row const parentRow = input.closest('tr'); console.log(`Value: ${input.value} | Row index: ${parentRow.rowIndex}`); }); console.log('All input values:', inputValues);
Bonus: Group Values by Row
If you need to organize values per row (instead of a flat array), iterate over rows first then their inputs:
const tableRows = receiptTable.querySelectorAll('tbody tr'); // Target data rows (adjust if your table uses <tbody>) const rowGroupedValues = []; tableRows.forEach(row => { const rowInputs = row.querySelectorAll('input'); const rowValues = Array.from(rowInputs).map(input => input.value); rowGroupedValues.push(rowValues); }); console.log('Values grouped by row:', rowGroupedValues);
Solution 2: jQuery (If Your Project Uses It)
jQuery makes selector syntax a bit cleaner—here’s how to do the same with it:
// Collect all input values into a flat array const inputValues = []; $('#receiptTable input').each(function() { inputValues.push($(this).val()); // Optional: Get row context console.log(`Value: ${$(this).val()} | Row index: ${$(this).closest('tr').index()}`); }); console.log('All input values:', inputValues);
Group by Row with jQuery
const rowGroupedValues = []; $('#receiptTable tbody tr').each(function() { const rowValues = []; $(this).find('input').each(function() { rowValues.push($(this).val()); }); rowGroupedValues.push(rowValues); }); console.log('Values grouped by row:', rowGroupedValues);
Key Notes
- Dynamic Inputs: If rows are added after page load (via AJAX or user actions), make sure to run this code after the new rows are inserted, or use event delegation if you need to react to input changes in real time.
- Target Specific Inputs: If you only want certain inputs (e.g., those with a specific
nameorclass), adjust the selector—for example:receiptTable.querySelectorAll('input[name="quantity"]')or$('#receiptTable input.quantity-input').
内容的提问来源于stack exchange,提问作者Kevz
相关产品推荐
相关产品推荐

