This example code features a nested <table>
within another <table>
.
The main issue concerns the click
listener for the #add
button. Specifically, the final if/else
statement in the function. When you execute this code and click the "Add TextField" button once or multiple times, you'll notice that the #remove
button, where show()
should be triggered, is only visible for the first matched selector, not all of them.
Essentially, the goal is to have the "Remove TextField" button displayed for all instances of the #remove
selector.
The question at hand is: why does this occur? And how can it be resolved?
$(document).on("click", "button#add", function() {
event.preventDefault();
var parentTable = $(this).parent().parent().parent().parent().parent().parent().parent().parent();
var lastTableRow = parentTable.children('tbody').children('tr:last');
// Adding the new row
parentTable.children('tbody').append(lastTableRow.clone());
// Resetting the lastRow variable
lastTableRow = parentTable.children('tbody').children('tr:last');
// Reset the fields
lastTableRow.find('table tbody tr td input').each(function() {
$(this).val('');
});
// Update numberOfRows variable
var numberOfRows = parentTable.children('tbody').children('tr').length;
alert("numberOfRows:" + numberOfRows); // Check
if (!(numberOfRows > 1)) {
$("#remove").hide();
} else {
$("#remove").show();
}
});
#outer-table {
padding: 20px;
border: 3px solid pink;
}
#inner-table {
border: 3px solid orange;
}
#remove {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="outer-table">
<tbody>
<tr>
<td>
<table id="inner-table">
<tbody>
<tr>
<td>
<p style="display:inline-block">Enter first complain:</p>
<input type="text" />
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
<button id="add">Add Textfield</button>
<button id="remove">Remove Textfield</button>
</td>
</tr>
</tfoot>
</table>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Table Footer</td>
</tr>
</tfoot>
</table>