-1

I have the following table:

<table class="table table-striped" id="table_tran">
    <thead>
        <th>Transformations</th>

    </thead>
        <tbody>

            <tr>
        </tbody>
    </table>

This table is filled with generated tds when a user do something.What i want is when a user click on a generated td to show the text of the td he clicked on.I am using the following javascript code:

$("#table_tran td").on("click",function(){
    alert($(this).html())
});

This code won't work on generated tds.Any ideas? If i use this:

 <table class="table table-striped" id="table_tran">
        <thead>
            <th>Transformations</th>

        </thead>
            <tbody>

                <tr><td>fxfjjf</td>
            </tbody>
        </table>

The code will work only for the td "fxfjjf"

cssGEEK
  • 994
  • 2
  • 15
  • 38

2 Answers2

3

The problem is that the td isn't there when you are trying to bind the click event. So you'll need event delegation. You were close.

Change

$("#table_tran td").on("click",function(){...

To

$("#table_tran").on("click","td",function(){...

This will trigger the event every time your table is clicked. And will check the "td" argument to see if it was a match, and if so will fire your callback as desired.

Mouser
  • 13,132
  • 3
  • 28
  • 54
bluetoft
  • 5,373
  • 2
  • 23
  • 26
3

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the event binding call.

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.

As you are creating table cell dynamically.

You need to use Event Delegation. You have to use .on() using delegated-events approach.

change you code to

$("#table_tran").on("click", "td", function(){
    alert($(this).html())
});
Satpal
  • 132,252
  • 13
  • 159
  • 168