I have a table which runs a function on click event of it’s row. It is working perfectly fine but when a tr is added to this table by AJAX then I am not able to fire click event of this row or we can say click event is not firing for this row besides other rows are still able to fire click event.
$('div.dashboard-content table.list tbody tr').click(function(){
var id = $(this).attr('id');
$('div.dashboard-content table.list tr td').css({'background': '#ffffff','font-weight':'normal'});
$('div.dashboard-content table.list thead td').css({'background': '#EFEFEF','font-weight':'bold'});
$('tr[id='+ id + '] td').css({'background': 'lightblue','font-weight':'bolder'});
$.get(
'index.php?route=sale/order/infoforhome&token=<?php echo $token; ?>',
{ 'order_id' : id },
function(data){
if(data)
{
$('#oder_detail').html
('<table>' +
'<tbody>' +
'<tr>'+
'<td style="font-weight:bold;">' +
'<?php echo $column_orderid; ?>:'+
'</td>'+
'<td>' +
data['orderid'] +
'</td>'+
'</tr>' +
'<tr>'+
'<td style="font-weight:bold;">'+
'<?php echo $column_customername; ?>:'+
'</td>'+
'<td>'+
data['name'] +
'</td>'+
'</tr>'+
'<tr>'+
'<td style="font-weight:bold;">'+
'<?php echo $column_shippingaddress; ?>: '+
'</td>'+
'<td>'+
data['address'] +
'</td>'+
'</tr>'+
'<tr>'+
'<td style="font-weight:bold;">'+
'<?php echo $column_telephone; ?>:'+
'</td>'+
'<td>'+
data['telephone'] +
'</td>'+
'</tr>'+
'<tr>'+
'<td style="font-weight:bold;">'+
'<?php echo $column_orderstatus; ?>:'+
'</td>'+
'<td>'+
data['orderstatus'] +
'</td>'+
'</tr>'+
'<tr>'+
'<td style="font-weight:bold;">'+
'<?php echo $column_ordertotal; ?>:'+
'</td>'+
'<td>'+
data['total'] +
'</td>'+
'</tr>'+
'</tbody>'+
'</table>');
}
else
{
$('#order_detail').html('Sorry No Details exists for this order in the database');
}
}, 'json');
});
function getLatestOrders() {
var last_order_id = $('div.dashboard-content table.list tbody tr:first').attr('id');
$.get(
"index.php?route=common/home/latest&token=<?php echo $token; ?>",
{'order_id' : last_order_id },
function (data) {
if (data) {
for (var i = 0; i < data.length; i++) {
$('div.dashboard-content table.list tbody tr:first').before(
'<tr id="' +
data[i]['order_id'] +
'"><td class="right">' +
data[i]['order_id'] +
'</td><td class="left">' +
data[i]['customer'] +
'</td><td class="left">' +
data[i]['status'] +
'</td><td class="left">' +
data[i]['date_added'] +
'</td><td class="right">' +
data[i]['total'] +
'</td><td class="right"> [<a href="' +
data[i]['action']['href'] + '">' +
data[i]['action']['text'] +
'</a>]</td></tr>'
);
}
}
}
}
You need to bind the click function to a parent element so the event can properly bubble. I can see no structure so I’m going to make some assumptions here.
the .on() method is used in versions later than 1.7 to handle event delegation. In previous versions, we use .delegate().