John Davidson

javascript - PHP - Capture Table Data During Form Submission that has no Inputs

0 comments
Message:


I have a simple web form that also includes a table that allows users to delete table rows before submitting the form. I need to capture the data from the table rows that exist when the form is submitted but as there are no form input fields in the table these are not showing in my request variables.


The table is pretty simple and looks like this:




<table class="table table-condensed table-striped table-bordered">
<thead>
<th class="text-center" scope="col">Code</th>
<th class="text-center" scope="col">Name</th>
<th class="text-center" scope="col">Part ID</th>

</thead>
<tbody>

<tr>
<td>ABC123</td>
<td>Widgets - Small</td>
<td>S2000</td>
</tr>
<tr>
<td>ZXR987</td>
<td>Bolts - Large</td>
<td>G5600</td>
</tr>


</tbody>
</table>


My Answer:
To capture the data from the table rows that exist when the form is submitted, you can use JavaScript to dynamically create hidden input fields with the data from the table rows before the form is submitted. Here's an example of how you can achieve this:

1. Add a hidden input field in your form to store the table data:

html



2. Add a JavaScript function to capture the table data and update the hidden input field before the form is submitted:

javascript
document.getElementById('your_form_id').addEventListener('submit', function() {
var tableData = [];
var tableRows = document.querySelectorAll('#your_table_id tbody tr');

tableRows.forEach(function(row) {
var rowData = [];
var cells = row.cells;

cells.forEach(function(cell) {
rowData.push(cell.textContent);
});

tableData.push(rowData.join(','));
});

document.getElementById('table_data').value = tableData.join(';');
});


Replace `'your_form_id'` with the ID of your form and `'your_table_id'` with the ID of your table.

3. When the form is submitted, the hidden input field `table_data` will contain the data from the table rows in a format that you can parse on the server side (e.g. comma-separated values for rows and semicolon-separated values for cells).

4. On the server side (in your PHP script), you can retrieve the table data from the `table_data` request variable and process it as needed.

This approach allows you to capture the data from the table rows that exist when the form is submitted, even though there are no form input fields in the table.

Rate this post

3 of 5 based on 5120 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us