darkromz
darkromz

Reputation: 27

jquery accessing elements of dynamic content

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>

.

Upvotes: 2

Views: 856

Answers (2)

Mathew Thompson
Mathew Thompson

Reputation: 56429

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

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

Upvotes: 1

VladL
VladL

Reputation: 13033

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

Upvotes: 0

Related Questions