Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the value of type input inside a table cell?

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?

like image 557
Heeiman Avatar asked Oct 14 '25 02:10

Heeiman


1 Answers

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()
}

Example:

$(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>
like image 91
Shidersz Avatar answered Oct 16 '25 17:10

Shidersz