0

What I'm trying to do with the following snippet should be self-explanatory

    <tbody id="slide-table-body">
    </tbody>                            
</table>
<button class="wp-core-ui button-primary" type="button" onclick="addAnotherSlide()">Add another carousel item</button>
<script type="text/javascript">
      var newRowHtml = '<tr><td>(assetprevurl)</td><td>(asseturl)</td><td><button type="button" class="wp-core-ui button-primary deleteSlideButton">Delete Slide</button></td></tr>';

      function addAnotherSlide() { jQuery('#slide-table-body').append(newRowHtml); }

      jQuery(function($){
           $('.deleteSlideButton').click(function() { $(this).closest('tr').remove();});
</script>  

My problem is that

$('.deleteSlideButton').click(function() { $(this).closest('tr').remove();} );

isn't deleting the row and I can't figure out why.

Jon P
  • 19,442
  • 8
  • 49
  • 72

2 Answers2

1

This is because you're adding the html after the DOM is loaded, try using Jquery on :

$( ".deleteSlideButton" ).on( "click", function() {
      console.log($(this));
});
code
  • 1,127
  • 7
  • 14
  • It probably has to do with the way you're traversing the DOM to try to remove(). It's not clear whether you're trying to delete the current it's on or some sibling. Either way, closest() is probably causing you problems as it's not very specific. This might guide you in the right direction: http://jqfundamentals.com/chapter/traversing-manipulating – Phillip Chan Oct 01 '15 at 00:48
0

It's cause you've attached an event handler to a newly created DOM element. Change it to:

$('.deleteSlideButton').on("click", function() {
  // do something
});

This may also help: Difference between .on('click') vs .click()

Community
  • 1
  • 1
Phillip Chan
  • 993
  • 7
  • 17