Reputation: 1652
Please consider the following code:
CODE:
$(document).on("click", "#add_new_item_ingredient", function() {
$(this).siblings("#ingredients_table").append('<tr><td style="width:20%"> <input type="text" id="option_item_costs_2" class="form-control" placeholder="£2.50"> </td><td style="width:50%"> <input type="text" id="option_item_desc_2" class="form-control" placeholder="Ex. Extra tomato"> <input type="hidden" id="option_item_id_2" value="-1"> </td></tr>');
});
$(document).on("click", "#remove_new_item_ingredient", function() {
$(this).siblings("#ingredients_table tr").each(function(index) {
alert("!");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-striped notifications" id="ingredients_table">
<tbody>
<tr>..</tr>
<tr>..</tr>
<tr>..</tr>
</tbody>
</table>
<button class="btn_1" id="add_new_item_ingredient">+ Ingredient</button>
<button class="btn_1" style="background:#C70000;" id="remove_new_item_ingredient">- Ingredient</button>
Adding new rows with the first button works great, however when I attempt to remove the last tr
element from the same table, it does nothing. I am now attempting to alert, for each tr
element found, but I get no alerts. I have tried getting the table row count which always returns 0, and also attempted trying to get the element with #ingredients_table >tbody >tr
I can confirm that both of the click events are firing correctly, and I can correctly select the table element, just none of the rows within.
Any advise would be greatly appreciated.
Upvotes: 2
Views: 78
Reputation: 31682
It's because the button #remove_new_item_ingredient
has no tr
siblings.
You either select the table first and then use find
to get the tr
's:
$(this).siblings("#ingredients_table").find("tr").each(function(index) {
or use the:
$("#ingredients_table tr").each(function(index) {
which is better in redability.
And as @T.J.Crowder mentioned:
You have two tbody
elements in your table (neither of them closed, probably a typo)
You're appending the rows to the table
, not the tbody
Upvotes: 2
Reputation: 410
Remove's handler $.siblings
looks for tr
elements on the same level as button, which is not the case. tr
s are in table, that is 2 levels down. So just modify your call to $(this).siblings("#ingredients_table").find('tr')
Upvotes: 1