我有动态行和列的表格,我试图通过循环遍历每个表格并将 HTML 表格转换为 Json,tr
并td
在文本框中查找值但没有运气。这是我的 js 代码。
$("#btn_Table2Json").click(function () {
var rows = [];
$('table.dynatable tbody tr').each(function (i, n) {
var $row = $(n);
if (n.className.toUpperCase() != "Prototype".toUpperCase() && n.className.toUpperCase() != "Header".toUpperCase()) {
$('table.dynatable tbody td').each(function (j, d) {
rows.push({
//Here id,Name,Address,Contact are dynamic.so need to find it inside of 'th' of table.
//but i am not being able to find it, so i just hard coded it :(
Id: $row.find('td:eq(0)').text(),
Name: $row.find('td:eq(1)').text(),
Address: $row.find('td:eq(2)').text(),
Contact: $row.find('td:eq(2)').text()
});
});
}
});
//debugger;
alert(JSON.stringify(rows));
//alert(table.toString());
});
对于上表 JSON 输出应为:
[{ID:"1",Name:"Bibek",Address:"lubhoo",Contact:"98411"},{ID:"4",Name:"Suraj",Address:"Sanagaun",Contact:"984511"}]
我的 Html 是(列和行是动态的)
<table class="dynatable">
<thead>
<tr class="Header">
<th id="AddRowTh"><button class="add">Add Row</button></th>
<th>ID <a href="#" class="RemoveColumn">Remove</a></th>
<th>Name <a href="#" class="RemoveColumn">Remove</a></th>
<th>Address <a href="#" class="RemoveColumn">Remove</a></th>
<th>Contact <a href="#" class="RemoveColumn">Remove</a></th>
<th id="AddColumnTh"><button style="width: 100px; height: 25px" class="addColumn">Add Column</button></th>
</tr>
</thead>
<tbody>
<tr class="prototype">
<td><p class="RowName"></p><a href="#" class="RemoveRow">Remove</a><!--<button class="remove">Remove</button>--></td>
<td><input type="text" name="id[]" value="0" class="id" /></td>
<td><input type="text" name="name[]" value="" /></td>
<td><input type="text" name="col4[]" value="" /></td>
<td><input type="text" name="col3[]" value="" /></td>
</tr>
</table>