-2

I have a script which dynamically adds rows to a table when a user clicks on certain div links on the page. I am now trying to add a remove button so the user can get rid of added rows they don't want, but I am having an issue with getting them to work.

The code I have used for removing the table row comes from here. The code I have is:

$('.addRow').click(function() {
      var tr = $(
      '<tr><td class="cat"></td>' 
      + '<td class="sel"></td>'
      + '<td><textarea name="paragraph[' + count + ']">Click to edit (id ' + count + ')</textarea><input type="hidden" name="catText[' + count + ']" class="hiddenCat"><input type="hidden" name="selText[' + count + ']" class="hiddenSel">'
      + '</td><td><button type="button" class="removebutton">Remove row</button></td></tr>');
      $('.mainTable > tbody:last').one().append(tr);
      tr.find(".cat").text($(this).closest("li.category").attr("title"));
      tr.find(".hiddenCat").val($(this).closest("li.category").attr("title"));
      tr.find(".sel").text($(this).closest("li.select").attr("title"));
      tr.find(".hiddenSel").val($(this).closest("li.select").attr("title"));
      count++;
    });

     $('.removebutton').click(function() {
      alert('Hello');
      var whichtr = $(this).closest("tr");       
      whichtr.remove();      
    });

The addRow function appends a table row to a selected table. Within one of the cells is a button with the 'removebutton' class. When this is clicked, it's supposed to remove the row. For testing purposes an alert message is used; however when I click on one of the buttons dynamically generated with addRow nothing happens.

When I statically add a button or link with the 'removebutton' class, the alert message displays.

Why is there an issue when creating the button through jQuery that stops it from working?

Community
  • 1
  • 1
Roy
  • 705
  • 2
  • 11
  • 32
  • possible duplicate of [jQuery - Click event doesn't work on dynamically generated elements](http://stackoverflow.com/questions/6658752/jquery-click-event-doesnt-work-on-dynamically-generated-elements) – Ram May 03 '13 at 15:45
  • do you have firebug installed? see anything in the firebug console ? – user1800937 May 03 '13 at 15:45

2 Answers2

2

Use .on for dynamic content:

$(document).on('click', '.removebutton', function() {
  alert('Hello');
  var whichtr = $(this).closest("tr");       
  whichtr.remove();      
});
tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • Works like a charm, thanks very much! Will accept as correct answer when SO lets me. – Roy May 03 '13 at 15:47
2

You need event delegation for dynamically created element's

$('.mainTable').on('click','.removebutton',function() {
  alert('Hello');
  var whichtr = $(this).closest("tr");       
  whichtr.remove();  
});

http://api.jquery.com/on/

Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111