JavaScript遍历表格函数:Symfony框架下多表格数据遍历需求
Traverse Dynamic Tables with Inputs in Your Symfony App
Here's a robust JavaScript solution to iterate through all your tables, collect input values, and structure the data meaningfully—perfect for your Symfony app's dynamic tables:
Step-by-Step Explanation & Code
First, update your form's onsubmit to pass the event object (we need this to prevent default submission):
<form onsubmit="runScript(event)"> <!-- Your table containers here --> </form>
Then add this JavaScript function (you can place this in a script tag at the end of your template or a dedicated JS file):
function runScript(event) { // Stop the form from submitting normally so we can handle data with JS event.preventDefault(); // Store all collected table data in this array const allTableData = []; // Target all table containers (adjust the selector if your div IDs follow a different pattern) const tableContainers = document.querySelectorAll('div[id^="tbl"]'); tableContainers.forEach(container => { const table = container.querySelector('table'); if (!table) return; // Skip if no table exists in the container // Extract column names from the table header const columnNames = Array.from(table.querySelectorAll('thead th')) .map(th => th.textContent.trim()); // Get all rows in the table body const tableRows = table.querySelectorAll('tbody tr'); // Process each row to collect input values const rowsData = Array.from(tableRows).map(row => { // Get all text inputs in the current row const rowInputs = row.querySelectorAll('input[type="text"]'); // Map input values to their corresponding column names return Array.from(rowInputs).reduce((rowObject, input, index) => { rowObject[columnNames[index]] = input.value.trim(); return rowObject; }, {}); }); // Add this table's data to the overall collection, including the table name allTableData.push({ tableId: container.id, rows: rowsData }); }); // Now you can use the collected data—here's how to log it for testing console.log('Collected Table Data:', allTableData); // Optional: Send the data to your Symfony backend via fetch // fetch('/your-symfony-route', { // method: 'POST', // headers: { // 'Content-Type': 'application/json', // 'X-CSRF-Token': '{{ csrf_token("your_intention") }}' // Don't forget Symfony's CSRF token! // }, // body: JSON.stringify(allTableData) // }) // .then(response => response.json()) // .then(result => console.log('Data submitted successfully:', result)) // .catch(error => console.error('Submission error:', error)); }
Key Features
- Flexible: Works with any number of tables, regardless of row count.
- Structured Data: Maps input values to their column names, making the data easy to work with in your Symfony backend.
- Symfony-Friendly: Includes a commented-out fetch example with CSRF token handling (critical for Symfony form security).
- Error-Resilient: Skips containers without tables to avoid runtime errors.
Adjustments You Might Need
- If your inputs aren't only text, modify the selector to
input(to include all input types) or add specific types likeinput[type="number"]. - If your table container IDs don't start with "tbl", update the
querySelectorAllargument to match your actual ID pattern (e.g.,div[data-table]if using data attributes).
内容的提问来源于stack exchange,提问作者Briggs Milburn
相关产品推荐
相关产品推荐

