I am dynamically adding to a transposed table. Adding the headers works; however when I add the table details (td) they appear under the table instead of to the right.
CSS to transpose table:
table { border-collapse: collapse; }
tr, tbody { display: block; float: left; }
th, td { display: block; border: 1px solid black; }
Table HTML:
<table>
<tr id="tableHeaders">
<!-- Place for exercise headers -->
</tr>
<tbody id="tableBody">
<tr>
<td>20/04/2021</td>
<td>20</td>
<td>10</td>
</tr>
<tr>
<td>27/04/2021</td>
<td>21</td>
<td>11</td>
</tr>
<!-- Place for exercise details -->
</tbody>
</table>
js to populate table:
//Populate the variable number of headers and keep count.
var numHeaders = 1;
$("<th>Date</th>").appendTo($("#tableHeaders"));
$.each(responseJson1a, function() {
$("<th>"+ this.edeType + " - " + this.edeUnit + "</th>").appendTo($("#tableHeaders"));
numHeaders++;
});
//Create an input detail cell for each header
$("<tr>").appendTo($("#tableBody"));
for(let i = 0; i < numHeaders; i++) {
$("<td><input></td>").appendTo($("#tableBody"));
}
$("</tr>").appendTo($("#tableBody"));
This is the result:
The table should look like:
This is what the table would look like when not transposed:
You are adding inputs inside tbody
not inside any tr tag . So , you can just use :last
this will refer tr tag which is added last and then inside this tr you can add your inputs .
Demo Code :
//just for demo.. var responseJson1a = [{ "edeType": "Speed", "edeUnit": "km/h" }, { "edeType": "Speed", "edeUnit": "km/h" }] var numHeaders = 1; $("<th>Date</th>").appendTo($("#tableHeaders")); $.each(responseJson1a, function() { $("<th>" + this.edeType + " - " + this.edeUnit + "</th>").appendTo($("#tableHeaders")); numHeaders++; }); $("<tr></tr>").appendTo($("#tableBody"));//new tr.. for (let i = 0; i < numHeaders; i++) { $("<td><input></td>").appendTo($("#tableBody tr:last")); //append to last tr which is added }
table { border-collapse: collapse; } tr, tbody { display: block; float: left; } th, td { display: block; border: 1px solid black; padding: 2px; height: 20px }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script> <table> <tbody id="tableBody"> <!--move it inside--> <tr id="tableHeaders"> </tr> <tr> <td>20/04/2021</td> <td>20</td> <td>10</td> </tr> <tr> <td>27/04/2021</td> <td>21</td> <td>11</td> </tr> <!-- Place for exercise details --> </tbody> </table>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.