Create a new row with jquery
You can create a new row in a table using jQuery by appending a new tr
element to the table. Here is an example:
<table id="myTable">
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
</thead>
<tbody>
<!-- existing rows go here -->
</tbody>
</table>
<script>
var newRow = $("<tr>");
newRow.append("<td>new cell 1</td><td>new cell 2</td><td>new cell 3</td>");
$("#myTable tbody").append(newRow);
</script>
This code creates a new tr
element and appends three td
elements to it. Then, it selects the tbody
element of the table and appends the new row to it.
You can also use the clone()
method to create a copy of an existing row and then modify it:
var existingRow = $("#myTable tbody tr:eq(0)").clone();
existingRow.find("td").eq(0).text("new cell 1");
existingRow.find("td").eq(1).text("new cell 2");
existingRow.find("td").eq(2).text("new cell 3");
$("#myTable tbody").append(existingRow);
This code clones the first row of the table, modifies the text of the cells, and then appends the modified row to the table.
You can also use a template engine like Handlebars or Mustache to create a new row with dynamic data:
<script id="rowTemplate" type="text/x-handlebars-template">
{{#rows}}
<tr>
{{#cells}}
<td>{{this}}</td>
{{/cells}}
</tr>
{{/rows}}
</script>
<script>
var data = [{"cell1": "value1", "cell2": "value2", "cell3": "value3"}];
var template = Handlebars.compile($("#rowTemplate").html());
var newRow = template(data);
$("#myTable tbody").append(newRow);
</script>
This code uses Handlebars to compile a template and then uses the template to generate a new row with dynamic data.