I am new to Javascript and hope someone here can help me with this.
I have an HTML page with a table on it and would like to use JS to dynamically add rows with certain content to the table's body.
So far I have the below code which is shortened here (in reality there are more rows and columns etc.) which is causing me the following issues:
- When I run this it inserts the dynamic HTML above the table instead of inside the table's body.
- It does not apply any styles to it (which are defined by the classes in my CSS) so it just shows the cells' content without applying border or column width styles etc. Do I have to tell it somehow that it has to apply the CSS styles to this as well ?
- Also, I was wondering if there is a way that in the first variable I don't have to list all numbers separately but instead just write the first (1) and last (5) number of a series as they are just simple sequences like 1, 2, 3, 4, 5.
Can someone tell me what I am doing wrong here ?
My JS:
$('#btnStart').on('click', function(){
var cols = [1, 2, 3, 4, 5];
var tbody = '';
var i;
for (i = 0; i < cols.length; i++) {
tbody += cols[i] + "<tr> \
<td class='td col1'>1</td> \
<td class='td col2'>2</td> \
<td class='td col3'><div contenteditable='true' class='editable'></div></td> \
</tr>";
}
$('#bodyCal').html(tbody);
});
My HTML:
<table class="tblCal">
<colgroup>
<col class="col1" />
<col class="col2" />
<col class="col3" />
</colgroup>
<thead>
<tr>
<th colspan="3" class="th th2">Col 1</th>
</tr>
</thead>
<tbody>
<div id="bodyCal"></div>
</tbody>
</table>
<tbody>instead