I have the following table:
<tbody id="TableBodyId">
<tr>
<td>First Value</td>
<td><input type="text" size="5" value="Second Value"></td>
</tr>
</tbody>
I want to know how I can extract both the first value
and the second value
using either JS
or Jquery
. Previously, my table looked like this:
<tbody id="TableBodyId">
<tr>
<td>First Value</td>
<td>Second Value</td>
</tr>
</tbody>
And to get the values, I did this using jQuery
:
var TableData = new Array();
$('#TableBodyId tr').each(function(row, tr)
{
TableData[row] = {
"firstValue" : $(tr).find('td:eq(0)').text(),
"secondValue": $(tr).find('td:eq(1)').text()
}
});
Then, I decided that I want to be able to change the values in the second cell, so I made it into:
<input type="text" size="5" value="Second Value"/>
The problem now, is that the tableData
on second cell is ""
(in other words, blank). To solve this, I tried to do:
"firstValue": $(tr).find('td:eq(0)').text(),
"secondValue": $(tr).find('td:eq(1)').val()
But no luck, Second Value still comes up as ""
. Any ideas on how to solve this?
You need to get the value from the <input>
element, like this:
TableData[row] = {
"firstValue" : $(tr).find('td:eq(0)').text(),
"secondValue": $(tr).find('td:eq(1) input').val()
}
$(document).ready(function()
{
var TableData = [];
$('#TableBodyId tr').each(function(row, tr)
{
TableData[row] = {
"firstValue" : $(tr).find('td:eq(0)').text(),
"secondValue": $(tr).find('td:eq(1) input').val()
}
});
console.log(TableData);
});
.as-console {background-color:black !important; color:lime;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody id="TableBodyId">
<tr>
<td>First Value</td>
<td><input type="text" value="Second Value"></td>
</tr>
</tbody>
</table>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With