Reputation: 3
In a table of id productTable, I am adding rows using the following jquery code:
$('#productTable').html("");
for (var i = 0; i < result.count; i++)
{
$('#productTable').append('<tr id=' + result.productArray[i].productID + 'class="product"><td><a> '+result.productArray[i].productName+'</a></td></tr>');
}
and I'm attaching a handler to these rows using:
$("#productTable").on("click","tr",function(event){
alert(this.id);
});
but the ID that I'm getting is of the table whereas I want the id of the row that is being clicked.
Help
Upvotes: 0
Views: 1362
Reputation: 318212
The issue is with what you're appending, it's not valid HTML
$('#productTable').append(
'<tr id=' + result.productArray[i].productID + 'class="product">
<td>
<a> '+result.productArray[i].productName+'</a>
</td>
</tr>'
);
look very carefully, there's no quotes around the ID, and no space separating the ID and the class.
Basically you end up with
<tr id=idclass="product">
<td>
<a>text</a>
</td>
</tr>
The correct code would be
$('#productTable').append('<tr id="' + result.productArray[i].productID + '" class="product"><td><a> '+result.productArray[i].productName+'</a></td></tr>');
Upvotes: 3
Reputation: 23816
Bind Event when you creating element dynamically. This is another way to do what you want.
$('#productTable').html("");
for (var i = 0; i < result.count; i++)
{
$('#productTable').append('<tr id=" + result.productArray[i].productID + " class="product"><td><a> '+result.productArray[i].productName+'</a></td></tr>');
$('#'+result.productArray[i].productID).bind('click',function(){
//put your code here
});
}
Upvotes: 0
Reputation: 121
Try This:
$('#productTable').html("");
for (var i = 0; i < result.count; i++)
{
var obj = $('<tr id=' + result.productArray[i].productID + 'class="product"><td><a> '+result.productArray[i].productName+'</a></td></tr>');
$(obj).click(function(event){
alert($(this).attr("id"));
});
$('#productTable').append(obj);
}
Upvotes: 0