We can use jQuery to add table rows dynamically in web application where the user may need to more rows if required.
Please follow below step to add dynamic row in table
Step 1 : Create table
Create basic page for your application need & add table structure like shown in following code.
Add button for add new row dynamically.
<table cellspacing="0" class="table table-no-bordered" id="account-table" width="100%">
<thead>
<tr>
<th width="60%">
A/C
</th>
<th width="30%">
Amount
</th>
<th width="10%">
Action
</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<td class="float-right" colspan="3">
<button class="btn btn-warning sb-btn-icon text-white-50 float-right" id="add-new-row" type="button">
<i class="fa fa-plus text-white-50">
</i>
</button>
</td>
</tr>
</tfoot>
</table>
Step 2 : Create hidden row
Create one row outside/end of your page of your table or div.
So we can make replica of that row & attach to end of our table.
Add "__row" to every dynamic variable or value for making or adding dynamic number for row.
<div class="d-none" id="account-table-div">
<table>
<tr id="tr__row">
<td>
<select class="form-control account_id___row" name="account_id[__row]" required="">
</select>
</td>
<td>
<input autocomplete="off" class="form-control" id="amount___row" name="amount[__row]" required="" step="0.01" type="number"/>
</td>
<td>
<button class="btn btn-danger btn-sm sb-btn-icon text-white-50 remove-row" data-id="__row" title="Remove" type="button">
<i class="fa fa-trash text-white-50">
</i>
</button>
</td>
</tr>
</table>
</div>
Step 3 : Add jQuery for new row
Now we make jQuery for add new row.
Attach event for button of add new row, just like following code.
We will get row structure from hidden div & attach end of our table.
We will replace "__row" to next number of row. For that we will use jQuery regular expression & replace method.
var counter = 0;
$(document).on("click", "#add-new-row", function() {
/*...get html...*/
var htmlRow = $("#account-table-div table").html();
htmlRow = htmlRow.replace(new RegExp("<tbody>", "igm"), "");
htmlRow = htmlRow.replace(new RegExp("</tbody>", "igm"), "");
htmlRow = htmlRow.replace(new RegExp("__row", "igm"), counter);
/*...append...*/
$("#account-table tbody").append(htmlRow);
counter++;
});
Step 4 : Remove row
If user add new row by mistake or no need of row then we have also provide remove functionality.
For that we need to add delete button to each & every row & assign unique number to identify current row.
Add following code after add new row functionality.
$(document).on("click", ".remove-row", function() {
var rowID = $(this).attr("data-id");
if (typeof rowID != "undefined") {
$("#tr" + rowID).remove();
}
});
That's all done here friends.