0

I have built a table from which I allow the user to add and delete rows. I want to be able to use the information that they input into these rows to make calculations, but it seems that this information isn't accessible since it has been dynamically added to the page.

Here are my add and delete functions:

$("a.deleteRow").live('click', function (){
    $(this).parent().parent().remove();
});

$("a.addRow").live('click', function (){
    $("table.moneyTable tr:last").prev('tr').before("<tr>[Long row formatting]</tr>");
});

I have some other dynamic content on the page, like various text input boxes that are select-box dependent, and these should all be accessible as well. They're not responding to my jQuery, though. Thoughts?

Jon
  • 3,154
  • 13
  • 53
  • 96

2 Answers2

4

Well...delegation in current versions of jQuery is performed with the .on() function. We delegate the event to a static parent object; document as used below.

$(document).on('click', 'a.deleteRow', function(){
  $(this).parent().parent().remove();
});

$(document).on('click', 'a.addRow', function(){
  $("table.moneyTable tr:last").prev('tr').before("<tr>[Long row formatting]</tr>");
});
Jared Farrish
  • 48,585
  • 17
  • 95
  • 104
Ohgodwhy
  • 49,779
  • 11
  • 80
  • 110
  • Hmm, this seems to be the agreed-upon solution, but simply switching my .live() to .on() didn't work. I'm guessing I did something wrong in my code, then. But any new rows and their data should be accessible through jQuery selectors? – Jon Aug 20 '12 at 01:41
  • @Jon let's see the code that's added the elements into the DOM after DOM load. Ensure that the functions above are wrapped in a `ready()` function, either short, or longhand: `$(document).ready(function(){` or `$(function(){`. Does the console return any errors? – Ohgodwhy Aug 20 '12 at 01:42
  • You need to src latest Jquery i.e. 1.7. beyond for `.on` api to work `:)` @Jon here `` – Tats_innit Aug 20 '12 at 01:42
  • 1
    @Jon Cooleos, enjoy! have fun! ohgodwhy `:P` for JQ 1.3.2 – Tats_innit Aug 20 '12 at 01:48
2

Try this please: 1.7.. above

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

Further if you keen to know why: What's wrong with the jQuery live method?

delegate et. al. jquery binding events to dynamically loaded html elements

<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>

Hope it fits your cause :) also not another good version is mentioned in the below post using document hence I won't update that in here!

$("a.deleteRow").on('click', function (){
    $(this).parent().parent().remove();
});

$("a.addRow").on('click', function (){
    $("table.moneyTable tr:last").prev('tr').before("<tr>[Long row formatting]</tr>");
});
Community
  • 1
  • 1
Tats_innit
  • 33,991
  • 10
  • 71
  • 77