I need to be able to click on a row in my table and return the value of its <td>
to the user. I'm using the Bootstrap Table cdn to construct my table. This dynamically creates a table body and table rows with data-index attributes.
I want to be able to click on an individual row and get the values of its cells. This is the current click event that I have set up.
let data = []
$("#table").on("click", function() {
const $ths = $(this).find("tr");
$.each($ths, function() {
const innerData = [];
$(this).find("td").each(function() {
innerData.push($(this).text().trim());
});
data.push(innerData);
})
console.log(data)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id='table'>
<tbody>
<tr data-index="0">
<td>ACB</td>
<td>1540</td>
<td>0784</td>
<td>E</td>
</tr>
<tr data-index="1">
<td>ACB</td>
<td>1559</td>
<td>0784</td>
<td>E</td>
</tr>
<tr data-index="2">
<td>ACB</td>
<td>2095</td>
<td>0784</td>
<td>A</td>
</tr>
<tr data-index="3">
<td>ADH</td>
<td>0001</td>
<td>0347</td>
<td>S</td>
</tr>
<tr data-index="4">
<td>ADH</td>
<td>1075</td>
<td>0347</td>
<td>E</td>
</tr>
<tr data-index="5">
<td>ADH</td>
<td>0001</td>
<td>0347</td>
<td>A</td>
</tr>
<tr data-index="6">
<td>ADH</td>
<td>1076</td>
<td>0347</td>
<td>E</td>
</tr>
<tr data-index="7">
<td>AHG</td>
<td>2136</td>
<td>0657</td>
<td>W</td>
</tr>
<tr data-index="8">
<td>AHG</td>
<td>1037</td>
<td>0657</td>
<td>E</td>
</tr>
<tr data-index="9">
<td>AHG</td>
<td>I013</td>
<td>0657</td>
<td>W</td>
</tr>
</tbody>
</table>
This click event will push all of the tr's into the data array. Like this
[
[],
[
"ACB",
"1559",
"0784",
"E"
],
[
"ACB",
"2095",
"0784",
"A"
],
[
"ACB",
"1540",
"0784",
"E"
],
[
"ADH",
"1076",
"0347",
"E"
],
[
"ADH",
"0001",
"0347",
"S"
],
[
"ADH",
"0001",
"0347",
"A"
],
[
"ADH",
"1075",
"0347",
"E"
],
[
"AHG",
"2136",
"0657",
"W"
],
[
"AHG",
"1038",
"0657",
"E"
],
[
"AHG",
"I013",
"0657",
"W"
]
]
I want to be able to get the individual td values when I click on a specific row and push them into the array one at a time, not all at once. Any advice on how to achieve this is greatly appreciated!