How to convert HTML table to Javascript Object with jQuery
An extension of this question.
My table is dynamic its cells has Html content like Input to enter descritpion and Select for dropdown selection.
So to get that html content to json object created this answered question.
A simple changing in the code and you can:
//
// for each table row in table body
//
var tbl = $('#students tbody tr').map(function (idxRow, ele) {
//
// start building the retVal object
//
var retVal = {id: ++idxRow};
//
// for each cell
//
var $td = $(ele).find('td').map(function (idxCell, ele) {
var input = $(ele).find(':input');
//
// if cell contains an input or select....
//
if (input.length == 1) {
var attr = $('#students thead tr th').eq(idxCell).text();
retVal[attr] = input.val();
} else {
var attr = $('#students thead tr th').eq(idxCell).text();
retVal[attr] = $(ele).text();
}
});
return retVal;
}).get();
console.log(tbl);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="students" border="1">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Grade</th>
</tr>
</thead>
<tbody>
<tr class="student">
<td>Oscar</td>
<td><select>
<option value="21">21</option>
<option value="23" selected>23</option>
<option value="32">32</option>
</select></td>
<td><input type="text" value="16.5"></td>
</tr>
<tr class="student">
<td>Antonio</td>
<td><select>
<option value="21">19</option>
<option value="23">23</option>
<option value="32" selected>32</option>
</select></td>
<td><input type="text" value="14"></td>
</tr>
<tr class="student">
<td>Jessica</td>
<td><select>
<option value="21" selected>21</option>
<option value="23">23</option>
<option value="32">32</option>
</select></td>
<td><input type="text" value="19"></td>
</tr>
</tbody>
</table>