I have a button which dynamically creates html content enclosed in <fieldset>
like this.:
<div id="box_parent"></div>
Javascript
var content =
'<fieldset>Some Content <input id="delete_row_box" type="button" value="Delete"></fieldset>';
$("#box_parent").append(content);
How can I make the dynamically created delete button only deletes the html block that it only belongs to?
I’m stuck on this function:
$(document).on("click", '#delete_row_box', function() {
console.log(this);
});
I think .remove()
should do it but I don’t know how to throw the correct reference
4
Answers
Whole Content
If you want to delete the whole content in box parent using jQuery, you should use this code:
One Row
Do not use ID for repeatable tags. It’s not working in JS. Just use a suitable class name as I used in examples
If you want a specific box appended to delete, then you should either give an id to the child during append or you should place the delete button inside the each box like a close button for each item.
If row’s container is direct parent of the button
Find the parent to remove using this code:
If row’s container is a grand parent of the button
Find the row you need to remove using this code:
fieldset
with the selector that matches your parent.Select its parent then delete the
fieldset
you addtry to add an id and remove that id.
This code should work fine and it will only delete "Some content", it will not remove the delete button you created. If you need to generate multiple content you can add an index when you create the content and a for or while loop to select the content to remove (with multiple delete button). You can even use a class instead of an id to delete them all in one go.