0

Please see this page which has this code:

<div class="pure-control-group query-brand-by-column">
    <!-- somethings else -->
    <div class="pure-u-1 pure-u-sm-1-24 control-group-sub">
        <a href="javascript:$(this).closest('.query-brand-by-column').remove();" class="pure-button danger">X</a>
    </div>
</div>

Clicking the X link should remove its ancestor div.query-brand-by-column as a whole but somehow it's not working. I've checked jQuery docs and this answer and the code seems absolutely all right to me but it simply doesn't work. Any idea?

Community
  • 1
  • 1
datasn.io
  • 12,564
  • 28
  • 113
  • 154

3 Answers3

3

this in href doesn't refers to anchor element, thus it doesn't work. It refers to window.

You should bind element event handler using jQuery.

Script

$(document).on('click', '.pure-button danger' function(e) {
    e.preventDefault();
    $(this).closest('.query-brand-by-column').remove();
});

HTML

<div class="pure-control-group query-brand-by-column">
    <!-- somethings else -->
    <div class="pure-u-1 pure-u-sm-1-24 control-group-sub">
        <a href="#" class="pure-button danger">X</a>
    </div>
</div>

I will not recommended, However you can use inline onclick handler.

<a onclick="$(this).closest('.query-brand-by-column').remove();" href='#' class="pure-button danger">X</a>
Satpal
  • 132,252
  • 13
  • 159
  • 168
1

Detach your javascript from your html and remove your item with a click event, right now you aren't triggering any click events:

<script>
$(function(){
 $('.pure-form').on('click','.query-brand-by-column a',function(){//this will create and delegate your click event to work on dynamically created items 
  $(this).closest('.query-brand-by-column').remove();
 });
});
</script>
madalinivascu
  • 32,064
  • 4
  • 39
  • 55
1

Here is your answer, Enjoy

  <a href="javascript:void(0);" onclick="return $(this).closest('.query-brand-by-column').remove();" class="pure-button danger">X</a>
Nitin Vaghani
  • 297
  • 4
  • 14