[英]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
. 我想知道如何使用JS
或Jquery
提取第first value
和second value
。 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
: 为了获得值,我使用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). 现在的问题是,第二个单元格上的tableData
是""
(换句话说,是空白)。 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 ""
. 但是没有运气,Second Value仍然出现为""
。 Any ideas on how to solve this? 关于如何解决这个问题的任何想法?
You need to get the value from the <input>
element, like this: 您需要从<input>
元素获取值,如下所示:
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>
Change 更改
"secondValue" :$(tr).find('td:eq(1)').val()
to 至
"secondValue" :$(tr).find('td input:eq(0)').val()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.