DataTable获取更新后行数据问题:调用rows().data()返回旧数据
Hey there! I totally get the frustration when you update form fields in your DataTable but rows().data() still spits out old values. Let's break down why this happens and how to fix it quickly.
Why This Happens
DataTable keeps its own internal cache of row data when it initializes. The rows().data() method pulls directly from this cache, not from the live DOM elements. So when you edit an input or select, the DOM updates but DataTable's cache doesn't—hence the stale data you're seeing.
Solution 1: Update DataTable's Cache in Real-Time
If you want to keep using rows().data() seamlessly, set up listeners for form field changes and update DataTable's internal data immediately. Here's how:
// Listen for changes in input/select fields inside the table $('#exampleTable').on('change', 'input, select', function() { const $row = $(this).closest('tr'); const table = $('#exampleTable').DataTable(); // Get the row and column indices for the updated field const rowIndex = table.row($row).index(); const cell = table.cell($(this).closest('td')); const colIndex = cell.index().column; // Update the cached data with the new value table.cell(rowIndex, colIndex).data($(this).val()); });
Now whenever you edit a field, DataTable's cache gets synced right away. Calling table.rows().data() will return the latest values just like you expect.
Solution 2: Directly Fetch Values from the DOM
If you only need to collect data once (like on form submission), skip the cache entirely and pull values straight from the DOM elements:
const table = $('#exampleTable').DataTable(); const freshData = []; // Loop through each row in the table table.rows().every(function() { const rowData = {}; // Iterate over each cell in the row this.nodes().to$().find('td').each((index, cell) => { const $cell = $(cell); const $input = $cell.find('input, select'); if ($input.length) { // Grab the current value from the form field rowData[`column${index}`] = $input.val(); } else { // Use plain text for non-form cells rowData[`column${index}`] = $cell.text().trim(); } }); freshData.push(rowData); }); // freshData now holds all the latest values from your table console.log(freshData);
Which Solution Should You Use?
- Go with Solution 1 if you frequently access table data after edits—it keeps everything in sync and makes subsequent
rows().data()calls fast. - Use Solution 2 for one-off data collection to avoid extra event listener overhead.
内容的提问来源于stack exchange,提问作者Vinay Kumar

