JSFiddle - React, Tailwind, and code Playground
by mori57
HTML
<table class="authors-list">
<!-- for one thing, let's separate our table structure a little better -->
<thead>
<tr>
<td>author's first name</td>
<td>author's last name</td>
</tr>
</thead>
<!-- ... in this way, you don't have to manually exclude the header rows from your count -->
<tbody>
<tr>
<td>
<input type="text" name="first_name" />
</td>
<td>
<input type="text" name="last_name" />
</td>
<td><a class="deleteRow"> x </a>
</td>
</tr>
</tbody>
</table>
JavaScript
jQuery(".authors-list tbody").on('change', 'input[name^="first_name"]', function (event) {
event.preventDefault();
// get the number of rows, here
var counter = $(".authors-list tbody tr").length;
// you don't need to wrap newRow in a jQuery() call... append() does that for you
var newRow = '<tr><td><input type="text" name="first_name' + counter + '" /></td><td><input type="text" name="last_name' + counter + '" /></td><td><a class="deleteRow"> x </a></td></tr>';
jQuery('.authors-list tbody').append(newRow);
});
jQuery(".authors-list tbody").on('click', '.deleteRow', function (event) {
// get the counter at the point in time when you're trying to test deletion
var counter = $(".authors-list tbody tr").length;
if (counter == 1) {
alert('form must have at least one row')
} else {
$(this).closest('tr').remove();
}
});