0

Really simple: with jQuery I add a new TR that has a delete button. But when delete button is clicked, nothing happens (should remove the newly created TR). I can’t get it work. I’m almost certain it has something to do with this:

$('.delete-data').on('click touchstart', '.add-new', function() {

My code:

// if clicked on new button add new TR
$('.add-new').on('click touchstart', function() {
  if ($(this).hasClass('company')) {
    newTr('company');
  } else {
    newTr('user');
  }
})

// adds new TR to table
function newTr(type) {
  var table = $('table');

  if (table.hasClass(type)) {
    table.find('tbody').append(
      '<tr contenteditable="true">
        <td>New ' + type + ' name</td>
        <td>License type</td>
        <td>0</td>
        <td>Expiry date</td>
        <td>xYsqffSX3X4a</td>
        <td class="delete-data" title="Delete this">&times;</td>
      </tr>'
    );
  }
}

// deletes data from table
$('.delete-data').on('click touchstart', '.add-new', function() {
  var parent = $(this).parent(),
      label = parent.find("td:first").html(),
      r = window.confirm("Permanently delete " + label + " and all its data?");

  if (r == true)
    parent.remove();
})

Any ideas? Thanks!


EDIT: Thanks to Barmar the solution is this one:

$('table').on('click touchstart', '.delete-data', function() {
3
  • 1
    .delete-data isn't a static element, therefore it can't be effectively used for event delegation. Commented Oct 7, 2013 at 20:33
  • as Kevin B mentions you want to use a element that does not change, like a parent element, body, document etc. $(document).on Commented Oct 7, 2013 at 20:35
  • @KevinB @PatrickEvans so the problem is because I have .delete-data on a <td> instead of something else like <button>? Commented Oct 7, 2013 at 20:36

2 Answers 2

1

Try:

$("table").on('click touchstart', '.delete-data', function() {
    ...
}

When you use event delegation, you must bind to a static element ($("table") in this case), and give a selector for the dynamic element (.delete-data) in the arguments.

Sign up to request clarification or add additional context in comments.

Comments

1

It's my first post on stackoverflow ;) Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to. Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. So, about you example:

$('.example_table').on('click touchstart', 'td.delete-data', function() {})

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.