tags:

views:

126

answers:

2

I have a table with one row in my HTML file. Now in jQuery I append lot of rows based on the data in the database. But the anchor tag which is created dynamically doesn't respond to events. How do I make this anchor tag respond to events?

jQuery part

//Appending rows from the Database

$('<tr> <td> </td> <td id="log'+i+'"><a href="viewlog.php" target="_blank">log</a></td></tr> ').appendTo('#container');

Event part in jQuery Now when I write a line of code like this it does not respond.

$('#container a ').click(function()
{

    alert("Coming here ");
});

//HTML

<html>
    <table id="container">
        <tr>
            <td>
                Name
            </td>
            <td>
                Link
            </td>
        </tr>
    </table>
</html>
+3  A: 

If you assign the click event at the beginning the elements created after won't get it.Try with:

$("#container a").live("click", function(){
  ...
});

in this way every time a link is created the event is attached to it (http://docs.jquery.com/Events/live#typefn).

mck89
After adding this code $('#container td').live("click",function() { alert("coming here"); }); the dynamically appended rows disappear from the html page. Is there something i am missing ?
mithunmo
+2  A: 

As mck89 suggests, the event will not be bound if you run the code before appending the new dom.

You can chain the binding of events or use the live function instead.

$('your html')
   .appendTo('#container')
   .find('a')
   .click(function() {
      alert('You clicked!');
   });
Mickel
Nice use of find()
Nerdling