Reputation: 306
I have a silly bug that I'm overlooking. I can add items to the form by clicking the plus button but I am having trouble removing items that I have added. Here is my code:
<script>
$(document).ready(function(){
var item_index=0;
$("#add_additional_item").click(function(){
item_index++;
$("#Additional_item").attr("placeholder", "Additional Item " + item_index);
$("#Additional_items_wrap p").attr("id", "remove_additional_item" + item_index);
$("#number_of_fields").attr("value", item_index);
$(this).parent().before($("#Additional_items_wrap").clone().attr("id","Additional_items_wrap" + item_index));
$("#Additional_items_wrap" + item_index).css("display","inline");
$("#Additional_items_wrap" + item_index + " :input").each(function(){
$(this).attr("name",$(this).attr("name") + item_index);
$(this).attr("id",$(this).attr("id") + item_index);
});
$("#remove_additional_item" + item_index).click(function(){
$(this).closest("div").remove();
item_index--;
});
});
});
</script>
the HTML:
<label>Add Additional Item:</label>
<input type="hidden" id="number_of_fields" name="number_of_fields">
<div id="Additional_items_wrap" class="hidden">
<input type="text" name="Additional_item" id="Additional_item">
<p class="icon-minus" id="remove_additional_item"></p>
</div>
<div id="input_add_item">
<p id="add_additional_item" class="icon-plus" style="float:right; cursor:pointer"></p>
</div>
Upvotes: 0
Views: 166
Reputation: 2771
You are trying to use jQuery with dynamic html, see here:
"The reason is that you cannot bind a handler to items that don't presently exist in the DOM" jquery click event not working for dynamic fields
Update: Here is an example of what I mean.
$(document).on("click", "#remove_additional_item" + item_index, function () {
alert ("You just hit the jackpot!");
});
Upvotes: 1