Jon
Jon

Reputation: 3184

How can I make dynamic HTML elements accessible via jQuery?

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?

Upvotes: 0

Views: 1031

Answers (2)

Tats_innit
Tats_innit

Reputation: 34107

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>");
});

Upvotes: 2

Ohgodwhy
Ohgodwhy

Reputation: 50777

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>");
});

Upvotes: 4

Related Questions