I have an HTML table, to which I would like to add or remove rows dynamically, using a select box with some basic javascript.
I am not adding single rows, but a group of similar rows at the same time. For example, if I already had one set, then added another, the result would like like this:
<tr>
<th colspan="2">Item 1</th>
</tr>
<tr>
<th>Title</th>
<td>X</td>
</tr>
<tr>
<th>Description</th>
<td>Y</td>
</tr>
<tr>
<th colspan="2">Item 2</th>
</tr>
<tr>
<th>Title</th>
<td>A</td>
</tr>
<tr>
<th>Description</th>
<td>B</td>
</tr>
To add the rows, I am using jQuery's clone method, so I need some sort of container element to go around the group of rows, however, everything I have tried (span, div, etc) has led to invalid HTML and not functioned correctly.
The only way I have managed to get it working is to have each set as a separate table, but this isn't really the effect I want.
Is there anything I can do to get around this?
<tr>: The Table Row element. The <tr> HTML element defines a row of cells in a table. The row's cells can then be established using a mix of <td> (data cell) and <th> (header cell) elements.
11.2. 5 Table rows: The TR element. The TR elements acts as a container for a row of table cells.
Defines a re-sizable table designed to display a list of database records.
The TR elements acts as a container for a row of table cells. The end tag may be omitted.
<tbody>
is the tag you’re looking for.
(And if your <th>
s are headings for their group of table rows, you can also use the scope
attribute to indicate this: <th colspan="2" scope="rowgroup">
.)
<tbody>
<tr>
<th scope="rowgroup" colspan="2">Item 1</th>
</tr>
<tr>
<th scope="row">Title</th>
<td>X</td>
</tr>
<tr>
<th scope="row">Description</th>
<td>Y</td>
</tr>
</tbody>
<tbody>
<tr>
<th scope="rowgroup" colspan="2">Item 2</th>
</tr>
<tr>
<th scope="row">Title</th>
<td>A</td>
</tr>
<tr>
<th scope="row">Description</th>
<td>B</td>
</tr>
</tbody>
Note however that within the table, you must either put all <tr>
s in a <tbody>
(or <thead>
or <tfoot>
) element, or none of them.
I.e. this is valid:
<table>
<!-- All <tr>s are inside <tbody>s -->
<tbody>
<tr>
<td></td>
</tr>
<tr>
<td></td>
</tr>
</tbody>
<tbody>
<tr>
<td></td>
</tr>
<tr>
<td></td>
</tr>
</tbody>
</table>
But this isn’t:
<table>
<!-- <tr>s and <tbody>s can’t be siblings. -->
<tr>
<td></td>
</tr>
<tbody>
<tr>
<td></td>
</tr>
<tr>
<td></td>
</tr>
</tbody>
</table>
Could use tbody
. Have you tried that?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With