Muhammad Zaheer
Muhammad Zaheer

Reputation: 3

Getting id of dynamically created row

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

Answers (3)

adeneo
adeneo

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

Manwal
Manwal

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
    });
}

Demo

Upvotes: 0

Lior Asta
Lior Asta

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

Related Questions