I need to dynamically add rows to a table. I know that I want a model row to look like the following:
<tr id="row">
<td><input type="text" name="name"/></td>
<td><span>TEXT HERE</span></td>
<td><input type="checkbox" name="asdf"/></td>
</tr>
I am wondering if I should just write code to reproduce this row from scratch or if I should use jQuery’s clone() method, as so:
//Would document this better in production
$('#row').clone().attr('id', 'row2').insertAfter('#row');
and then make sure that the original #row element was kept hidden with CSS.
Generalizing this question, would having a hidden DOM element and then cloning that element when it is needed a good practice for jQuery? Or is there a cleaner solution for this type of problem?
Thanks!
Short of hardcoding the format into JavaScript, this is really the best way to go about it.
The other way you could do it is by copying an existing row (of data) and removing all the text from the elements. Then you get a clone without the invisible row.
There are also plugins to handle this, like
dynoTableand others.