I have table with dynamic Rows and columns,i was trying to convert HTML table to Json by looping through each tr
and td
and finding values inside textbox but with no luck.Here is my js code.
$("#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());
});
For above table JSON output should be:
[{ID:"1",Name:"Bibek",Address:"lubhoo",Contact:"98411"},{ID:"4",Name:"Suraj",Address:"Sanagaun",Contact:"984511"}]
My Html is (columns and rows are dynamic)
<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>