function AddRow() {
$('#myDynamicTable tr:last').after('<tr><td class="itemName"><input type="text" style="width: 300px;"/><td class="itemQty"><input type="text" style="width: 50px;"/></td></td> </tr>');
$("#myDynamicTable").show();
}
单击按钮后,我将调用上面的函数,将一行添加到 html 表中。该表包含手动填写的 itemName 和 itemQty 列。
当我添加完所需的任意数量的行及其列值后,单击另一个按钮,我想读取表中的行值并将它们保存到数据库中。
最好还确保一行中的 itemName 和 itemQty 都有值,并且 itemQty 必须为数字。
var arrItems = [];
$('#myDynamicTable').find('tr').each(function () {
var row = $(this);
var item = new GatePassItemsViewModel("", "", $.trim(row.find(".itemName").html()), $.trim(row.find(".itemQty").html()));
arrItems.push(item);
});
我已经尝试了上面的代码,但是 $.trim(row.find(".itemName").html())
和 $.trim(row.find(". itemQty").html())
返回一个空字符串。
有人知道我如何成功地将表行读取到我的 arrItems
变量中吗?
下面是表格 html
<table id="myDynamicTable" class="displaynone">
<tbody>
<tr>
<th style='width:220px;'><b>Item</b></th>
<th style='width:15px;'><b>Quantity</b></th>
</tr>
</tbody>
</table>
最佳答案
我不知道为什么你的 .html()
调用不会返回任何内容,但我可以看到您遇到问题的一些原因。
主要问题是 row.find(".itemName").html()
将/应该返回表格单元格包含的 html,即 <input... />
,而您想要的是该输入元素的值。所以改成row.find(".itemName input").val()
(即定位输入元素并读取其值)对于这两种情况,您应该处于更好的状态。
要验证值,您可以简单地执行以下操作:
...
var row = $(this),
itemText = $.trim(row.find(".itemName input").val()),
qty= $.trim(row.find(".itemQty input").val());
if(itemText.length === 0 || !qty.match(/\d+/)) {
//Handle the problem of invalidity
}
这测试了 trim 后的 item
长度大于零且 qty
是一个整数(仅由一位或多位数字组成)。
其他问题/评论:
- 内部
AddRow()
,您的表格单元格以某种方式嵌套。您需要在打开第二个单元格之前关闭第一个单元格(并删除最后一个 double</td>
) - 行
$.trim(row.find(".searchFirstName").html());
不会有任何效果,因为它只返回 trim 后的值,不会更改您正在 trim 的变量或类似值。
关于javascript - 如何使用 jQuery 读取动态 html 表格行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29076765/