2

I am very new to jQuery, and am having trouble accessing elements of dynamic content. As you can see below, I have created a basic table contained within a div which is already present when you run the code. when you click on any cell, an alert prompt displays the text of that cell. However, if I create the table after the page has loaded (clicking on the button) and then click on the cells, I cant get the same result.

<script>
    $(document).ready(function() {
        $("#div1 td").click(function() {
            alert($(this).text());
        })

        $("#div2 td").click(function() {
            alert($(this).text());
        })

        $("#createtable").click(function () {
            $("#div2").html("<table id=\"table2\" border=\"1\"><tr><th>Table</th><th>2</th></tr><tr><td>January</td><td>$100</td></tr></table>");           
        })

    });
</script>

<div id="div1">
    <table id="table1" border="1">
      <tr>
        <th>Table</th>
        <th>1</th>
      </tr>
      <tr>
        <td>January</td>
        <td>$100</td>
      </tr>
      <tr>
        <td>February</td>
        <td>$80</td>
      </tr>
    </table>
</div>

<br>
<button id="createtable">Generate Table</button>
<div id="div2">DYNAMIC CONTENT</div>

.

Phillip
  • 1,969
  • 1
  • 22
  • 38
darkromz
  • 27
  • 4
  • possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Stephan Muller May 01 '15 at 09:52

2 Answers2

1

You need to apply event delegation for elements that are dynamically added to the DOM:

$(document).on("click","#div2 td", function() {
    alert($(this).text());
});
mattytommo
  • 52,879
  • 15
  • 115
  • 143
0

The event handlers are registered at the document load. You should re register them after replacing the context so you are better to put the code in the separate function and call it at every place you are replacing the affected elements

function regHandlers()
{
        $("#div1 td").click(function() {
            alert($(this).text());
        })

        $("#div2 td").click(function() {
            alert($(this).text());
        })
}

$(document).ready(function() {

        regHandlers();

        $("#createtable").click(function () {
            $("#div2").html("<table id=\"table2\" border=\"1\"><tr><th>Table</th><th>2</th></tr><tr><td>January</td><td>$100</td></tr></table>");  

        regHandlers();
        })
});
VladL
  • 11,959
  • 10
  • 58
  • 82