You can fetch the ids and classes of each tr
entry in your table by using the following function:
/* The function that fetches the data. */
function fetchData() {
var
/* Create an object to store the data. */
data = {},
/* Get every 'tr' element of the 'tbody'. */
elements = document.querySelectorAll("#tbody > tr");
/* For each element, save the id as a property & the class as a value in the obj. */
[].forEach.call(elements, (element) => data[element.id] = element.className);
/* Stringify and return the data to pass them over to the server. */
return JSON.stringify(data);
}
The above function stores the data as property-value pairs in an object and also stringifies the object, so that you can pass that to the server. Then you can easily the access in PHP with a foreach as
construct:
Example:
foreach ($data as $id => $class) {
# ...
}
Snippet:
/* The function that fetches the data. */
function fetchData() {
var
/* Create an object to store the data. */
data = {},
/* Get every 'tr' element of the 'tbody'. */
elements = document.querySelectorAll("#tbody > tr");
/* For each element, save the id as a property & the class as a value in the obj. */
[].forEach.call(elements, (element) => data[element.id] = element.className);
/* Stringify and return the data to pass them over to the server. */
return JSON.stringify(data);
}
<table class="table -dark -striped" id="datatable">
<thead></thead>
<tbody id='tbody'>
<tr id="1" class="lunch"></tr>
<tr id="2" class="breakfast"></tr>
<tr id="3" class="brunch"></tr>
<tr id="4" class="dinner"></tr>
<tr id="5" class="supper"></tr>
</tbody>
</table>
<button onclick = "console.log(fetchData())">Fetch Table Data</button>
6
solved Store tr’s ID and Class into a js array and read it in php [closed]