user784637
user784637

Reputation: 16092

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?

Upvotes: 2

Views: 414

Answers (2)

gdoron
gdoron

Reputation: 150253

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

Upvotes: 4

crush
crush

Reputation: 17013

Why not use

$("#myTable tbody tr").click(function() {});

instead?

Upvotes: 0

Related Questions