0

I have a table like

<table class="table-striped col-lg-12" id="resultsTable" >
    <thead>
        <tr>
            <th>
                Include? 
            </th>
            <th>
                Organization
            </th>
            <th>
                Category
            </th>
            <th>
                Orginal File Name 
            </th>
            <th>
                Link to File on Server
            </th>
            <th>

            </th>
        </tr>
    </thead>
    <tbody id="results">
        <tr>
        </tr>           
    </tbody>
</table>

and the tbody gets built out with buttons inside its tds after the user has triggered a particular event. I think the reason that my

$(function () {
    $('table button').click(function () {
        console.log("ok, it got clicked");
        $('#file2Download').val($(this).closest('tr').find('td:first').text());
        $(this).parents('form:first').submit();
    });
});

isn't working is because the tds aren't in the DOM on page load. Is there a good workaround for this or do I need to add in hidden tds or what?

user4905335
  • 371
  • 2
  • 13

2 Answers2

0

Yes, you can use event delegation.

$("table").on("click","td",function(evt){ ...
PeeHaa
  • 71,436
  • 58
  • 190
  • 262
user2182349
  • 9,569
  • 3
  • 29
  • 41
0

In a way. It's called event delegation. The idea is to bind to an already existing parent element, but make sure the actual targets of the events match a specified selector. This works because events propagate upwards all the way to the root element of the DOM by default.

Using jQuery's .on() instead of .click, you can easily do this:

$(function () {
    $('table').on('click', 'button', function () {
        console.log("ok, it got clicked");
        $('#file2Download').val($(this).closest('tr').find('td:first').text());
        $(this).parents('form:first').submit();
    });
});

To answer the actual question you asked, no, you cannot attach events to elements that don't exist yet.

MildlySerious
  • 8,750
  • 3
  • 28
  • 30