Dynamically add new table row jquery
You can dynamically add a new table row using jQuery by using the append()
or appendTo()
method. Here is an example:
<table id="myTable">
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
var newRow = "<tr><td>New Row</td><td>New Row</td><td>New Row</td></tr>";
$("#myTable tbody").append(newRow);
</script>
This will add a new row to the table with the text "New Row" in each column.
Alternatively, you can use the appendTo()
method to add the new row to the table:
var newRow = $("<tr><td>New Row</td><td>New Row</td><td>New Row</td></tr>");
$("#myTable tbody").append(newRow);
You can also use a loop to add multiple rows to the table:
for (var i = 0; i < 5; i++) {
var newRow = $("<tr><td>New Row " + i + "</td><td>New Row " + i + "</td><td>New Row " + i + "</td></tr>");
$("#myTable tbody").append(newRow);
}
This will add 5 new rows to the table with the text "New Row 0", "New Row 1", etc.
You can also use a template engine like Handlebars or Mustache to generate the new row dynamically:
var newRow = Handlebars.compile("<tr><td>{{name}}</td><td>{{age}}</td><td>{{ occupation}}</td></tr>")({
name: "John",
age: 30,
occupation: "Developer"
});
$("#myTable tbody").append(newRow);
This will add a new row to the table with the values "John", 30, and "Developer" in each column.
You can also use jQuery's tmpl
function to generate the new row:
var newRow = $.tmpl("<tr><td>{{name}}</td><td>{{age}}</td><td>{{ occupation}}</td></tr>", {
name: "John",
age: 30,
occupation: "Developer"
});
$("#myTable tbody").append(newRow);
This will add a new row to the table with the values "John", 30, and "Developer" in each column.