Convert Html Table to Json when the column has input fields, linput text or select

戏子无情 提交于 2019-12-11 01:48:39

问题


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.


回答1:


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>


来源:https://stackoverflow.com/questions/44313731/convert-html-table-to-json-when-the-column-has-input-fields-linput-text-or-sele

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!