Search code examples
javascripthtmljspstruts

How do i get the values from each row of a table and store them in a js array


I have this code that generates an html table and i want to get all the data from the rows when a button is clicked and store it in a js array.

    <table cellpadding="0" cellspacing="0" width="25%" style="margin-top: 3em;" align="center">
<tr align="center">
    <td>&nbsp;</td>
    <td colspan="2" style="font-size:small;">Anualitat seleccionable</td>   
</tr>

<tr align="center">
    <td class="tau4">&nbsp;</td>
    <td class="tau4">Empleat</td>
    <td class="tau4">Gestor</td>    
</tr>
<logic:iterate id="i" name="anys_irpf" indexId="count">
    <tr align="center" class="dadesAnys">
        <td class="tau2" width="30%">${i.any}</td>
        <td class="tau2" width="35%">
            <c:choose>
                <c:when test="${i.anyEmpleat == 1}">
                    <input type="checkbox" id="cbox1" value="cbox1" checked>
                </c:when>
                <c:otherwise>
                    <input type="checkbox" id="cbox1" value="cbox1">
                </c:otherwise>
            </c:choose>
        </td>
        <td class="tau2" width="35%">
            <c:choose>
                <c:when test="${i.anyGestor == 1}">
                    <input type="checkbox" id="cbox2" value="cbox2" checked>
                </c:when>
                <c:otherwise>
                    <input type="checkbox" id="cbox2" value="cbox2">
                </c:otherwise>
            </c:choose>
        </td>
    </tr>
</logic:iterate>
</table>

this is the code that generates the table.


Solution

  • var myTab = document.getElementById('tableID');
            var tableData = [];
        // LOOP THROUGH EACH ROW OF THE TABLE AFTER HEADER.
        for (i = 1; i < myTab.rows.length; i++) {
    
            // GET THE CELLS COLLECTION OF THE CURRENT ROW.
            var objCells = myTab.rows.item(i).cells;
    
            // LOOP THROUGH EACH CELL OF THE CURENT ROW TO READ CELL VALUES.
            for (var j = 0; j < objCells.length; j++) {
                tableData.push(objCells.item(j).innerHTML);
                }
    
        }