Search code examples
javascriptjqueryeventslive

Dynamically created table via ajax breaks .on functionality


I'm using ajax to dynamically create a table. When someone enters a query, a table (data) is created and replaces the contents inside #content-display:

function searchQuery(query){    
    $.ajax({
      url: "search.php",
      data: {term: query},
      success: function(data){
          $("#content-display").html(data);
      },
      dataType: 'html'
    });     
}

When someone clicks on an entry in the table, I want to alert the user of what they clicked on:

$(document).ready(function(){    
    $("#myTable tbody tr").on('click', function (){    
        alert($(this).children(":first")text());       
    });    
});

However the .on method is not working for me. When I replace .on with .live it alerts the user of what they just clicked on but since .live is deprecated, how do I go about changing the syntax of the .on method to get it to work?


Solution

  • $(document).ready(function(){    
        $("#content-display").on('click', '#myTable tbody tr', function (){    
            alert($(this).children(":first").text());       
        });    
    });