So first you must declare a global counter for that window.globalCounter = 2;
where you'll store the rows counter. (what index will have the added row)
Then when you add you increment that window.globalCounter++
.
And when you delete, you must fetch the currentRow, decrement the counter, and refactor the indexes.
$("tbody").on("click", "#delete", function (ev) {
// delete row
var $currentTableRow = $(ev.currentTarget).parents('tr')[0];
$currentTableRow.remove();
window.globalCounter--;
// refactor indexes
$('table').find('tr').each(function (index) {
var firstTDDomEl = $(this).find('td')[0];
var $firstTDJQObject = $(firstTDDomEl);
$firstTDJQObject.text(index + 1);
});
});
Here is a working code snippet.
window.globalCounter = 2;
$(document).ready(function () {
$("#add").on("click", function () {
var data = '<tr><td>' + window.globalCounter + '</td><td><input type="text" id="name2" value=""/></td><td><input type="text" id="phone2" value=""/></td><td><input type="text" id="email2" value=""/></td><td><button id="delete">Delete</button></td></tr>';
$("tbody").append(data);
window.globalCounter++;
});
$("tbody").on("click", "#delete", function (ev) {
var $currentTableRow = $(ev.currentTarget).parents('tr')[0];
$currentTableRow.remove();
window.globalCounter--;
$('table').find('tr').each(function (index) {
var firstTDDomEl = $(this).find('td')[0];
var $firstTDJQObject = $(firstTDDomEl);
$firstTDJQObject.text(index + 1);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button id="add">Add Row</button>
<table>
<tbody>
<tr>
<td>1</td>
<td>
<input type="text" id="name1" value="" />
</td>
<td>
<input type="text" id="phone1" value="" />
</td>
<td>
<input type="text" id="email1" value="" />
</td>
<td>
<button id="delete">Delete</button>
</td>
</tr>
</tbody>
</table>
Here you have an alternative working jsfiddle: https://jsfiddle.net/cn5p4oke/
Of course you must adjust the phone2, email2, name2 ids.
Please note that i used jQuery 2.1.0.