Add new table row on click jquery
Here is an example of how to add a new table row on click using jQuery:
<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>
$(document).ready(function() {
$('#myTable').on('click', 'tr:last', function() {
var newRow = $('<tr><td>new value 1</td><td>new value 2</td><td>new value 3</td></tr>');
$(this).after(newRow);
});
});
</script>
In this example, we are using the on
method to attach an event listener to the last row of the table (tr:last
). When the row is clicked, we create a new row using jQuery and append it after the clicked row using the after
method.
You can also use append
method instead of after
to add the new row at the end of the table.
$(this).append(newRow);
You can also add a button or a link inside the table row and use that as the trigger to add a new row.
<table id="myTable">
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>existing value 1</td>
<td>existing value 2</td>
<td><button class="add-row">Add Row</button></td>
</tr>
</tbody>
</table>
<script>
$(document).ready(function() {
$('#myTable').on('click', '.add-row', function() {
var newRow = $('<tr><td>new value 1</td><td>new value 2</td><td>new value 3</td></tr>');
$(this).closest('tbody').append(newRow);
});
});
</script>
In this example, we are using the closest
method to find the tbody
element that contains the clicked row, and then appending the new row to it using the append
method.