Aubergine Aubergine - 5 months ago 19
jQuery Question

jquery remove by parent div

Please consider following snippet:

<div class="row">
<div class="span12">
<div class="control-group">
<label class="control-label">Person Name</label>
<div class="controls">
<input type="text" class="input-medium">
</div>
</div>
</div>
</div>


The classes belong to grid-based css framework named 'bootstrap' and are used for positioning and styling.

The 'row' is inside of the single form. The form provides input for many persons. Each 'row' corresponds to a single person with its input details. (in this example I have only one property for simplicity - 'Person Name') So I can have many snippets/'rows' like this in a single form.

What I would like to do is to create a button which would be inside every 'row' and whenever it is clicked it would delete the entire row in which it resides, but would not affect other rows which belong to other persons' input details.

So far as I understood the easiest option would be usage of jQuery'.remove' method. However it would require id enumeration of every 'row' in this case, which I can generate on server-side, but not in this case, lets just assume that it is not allowed - I don't have 'id' attributes and I can't add them, so I can't point function at the row id to delete. If I fetch class to '.remove' method the button will obviously delete all the rows.

Just to illustrate the situation. Multiple rows, notice the buttons.

<form>
<div class="row">
<div class="span12">
<div class="control-group">
<label class="control-label">Person Name</label>
<div class="controls">
<input type="text" class="input-medium">
</div>
<div class="control-group">
<div class="controls">
<button type="button" onclick="deleteTheEntireRow()" class="btn btn primary">Delete Person</button>
</div>
</div>
</div>
</div>
<div class="row">
<div class="span12">
<div class="control-group">
<label class="control-label">Person Name</label>
<div class="controls">
<input type="text" class="input-medium">
</div>
<div class="control-group">
<div class="controls">
<button type="button" onclick="deleteTheEntireRow()" class="btn btn primary">Delete Person</button>
</div>
</div>
</div>
</div>
</form>


I apologise for formatting.

Essentially what a button must do:
detect and select just its fourth parent 'row', so I could apply `.remove' method.

kei kei
Answer
$("button").on("click", function(e) {
    $(this).closest("div.row").remove();
    e.preventDefault();
});‚Äč

I've remove the onclick property in the HTML by the way

DEMO