1

Using the deprecated .live() method I am able to make this work exactly as I would like however it's not ideal to keep it this way. I've found similar questions suggesting to use the $(".update").on() method or to call $(document).on('click', $('.update'), function()...) however I wasn't able to make any of the solutions work. The best I was able to do was return the full table but never able to get my snap.key. Any suggestions to make this work with any besides .live() would be very much appreciated.

  <table id="itemTable">
    <thead>
    <tr>
      <th>Item</th>
      <th>Cost</th>
      <th>Quantity</th>
      <th></th>
    </tr></thead>
    <tbody id = "tableBody">
    </tbody>
  </table>

Firebase call:

db.on('child_added', snap => {
    $('#tableBody').append('<tr><td class="up"><span>' + snap.key + '</span></td><td><button type = "button" class="update">Update</button></td></tr>');
});

button handler:

$(".update").live('click',function() {
  var $row = $(this).closest("tr");   // Find the row
  var $text = $row.find(".up").text(); // Find the text
  console.log($text);
});
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • My guess is that the `.update` element doesn't exist until after the Firebase call completes, so `click` and `on`, which only attach to items that currently exist on the page, had nothing to attach to. The deprecated `live` works for you because it attaches to the selection "now and in the future", instead of just "now". You can attach `click` or `on` to a parent element, and specify which child selection it should actually listen for. See this post: https://stackoverflow.com/questions/1359018/in-jquery-how-to-attach-events-to-dynamic-html-elements –  Jan 10 '19 at 22:20

1 Answers1

0

You want:

$(document).on('click', '.update', function(){...});

Note that the 2nd argument to on is a selector, whereas you were passing $('.update').

Madbreaks
  • 19,094
  • 7
  • 58
  • 72