Sideshow
Sideshow

Reputation: 1351

jQuery remove div onclick

I can't seem to get my jQuery right to remove a div when I delete something

Code is:

<div class="amend_order" data-item_key="1367264719mz7">
    <p>Home Made Ice Cream</p>
    <p class="small_text">Pistachio</p>
    <p>
        <a class="edit_item ui-link" href="javascript:void(0);">Edit</a>
        ----
        <a class="deleter ui-link" href="javascript:void(0);">Delete</a>
    </p>
</div>

I have tried using

$(this).closest('div').remove();

unfortunately this does not work.

Basically there is a list of several divs and I just want them to disappear when clicked.

Upvotes: 1

Views: 20631

Answers (4)

Simone Pessotto
Simone Pessotto

Reputation: 1581

Try this:

$('.deleter').on('click', function(){
  $(this).parent().parent().remove;
})

Live Sample

Upvotes: 0

Ian
Ian

Reputation: 50905

If your container divs are dynamically added, you need to use event delegation. Try this:

$("#container").on("click", ".amend_order .deleter", function () {
    $(this).closest("div").remove();
});

DEMO: http://jsfiddle.net/m6jVP/

If they're added dynamically, then the event binding won't actually find any elements and therefore won't execute when they're clicked. This event handling runs for any elements inside of #container that match the selector .amend_order .deleter when they are clicked.

You can replace #container with a selector that matches a stable (static) element containing these divs you're targeting, using document if necessary.

Upvotes: 5

Nedudi
Nedudi

Reputation: 5949

HTML

<div class="amend_order" data-item_key="1367264719mz7">
    <p>Home Made Ice Cream</p>
    <p class="small_text">Pistachio</p>
    <p>
    <a class="edit_item ui-link" href="javascript:void(0);">Edit</a>
    ----
    <a class="deleter ui-link" href="javascript:void(0);">Delete</a>
</p>
</div>

JS

$('.deleter').on('click', function(){
  $(this).closest('div').remove();
})

Live sample http://jsfiddle.net/Ny346/

Upvotes: 1

DextrousDave
DextrousDave

Reputation: 6793

Try pointing to the div:

$('div.amend_order').click(function(){
   $(this).remove();
});

or when clicking on the delete button:

$('a.deleter.ui-link').click(function(){
   $(this).parent('div').remove();
});

Upvotes: 0

Related Questions