I have a table row that I am creating on Ajax call. I would want to associate an onclick event. I am unable to pass an element from an array which I am traversing (which d[i] as per the code shown below).
So I am unable to grab the array element in the click event:
var d = $.parseJSON(data.codes);
for (var i = 0; i < d.length; i++) {
var currentRow = $('<tr>');
currentRow.append($('<td>').html(d[i].id));
currentRow.attr("class", "sourceCodeRow grid-row");
currentRow.append($('<td>').html(d[i].name));
currentRow.append($('<td>').html(d[i].description));
currentRow.click(function (f) {
//want to display name from d[i]
// alert(d[i].name);
});
$('#table-id').append(currentRow);
}
The reason this isn’t working is because your for loop index is no longer what you are expecting, as the for loop has finished looping once the row is clicked. You need to set your name to a variable that can be accessed inside the click event, I would just store the name in the data:
or if you need access to the whole object, just set that instead: