简体   繁体   中英

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?

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> 

Change

"secondValue" :$(tr).find('td:eq(1)').val()

to

"secondValue" :$(tr).find('td input:eq(0)').val()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM