Reputation: 3067
I need to pass row parameters to my onclick function.
this is my code:
function renderHostTableRowJob (dataTable) {
for (var i in dataTable) {
var notification = dataTable[i];
var row = document.createElement("tr");
var cell = document.createElement("td");
cell.innerText = notification["Name"];
row.appendChild(cell);
var cell = document.createElement("td");
cell.innerText = notification["State"];
row.appendChild(cell);
var cell = document.createElement("td");
cell.innerText = (notification["NotificationReceived"] === true) ? "Received" : "Missing";
row.appendChild(cell);
row.onclick = function() {alert(notification["Name"]);};
$("#" + notification["Client"] + "_TableJobDetails > #" + notification["Client"] + notification["HostFormated"] + "_TableBodyJobDetails")[0].appendChild(row);
}
}
At the moment all my row.onclick = function() {alert(notification["Name"]);};
are returning the value for the last iteration in my loop...
QUESTION: How can I send my values to the click event on each iteration?
thanks
Upvotes: 0
Views: 694
Reputation: 3067
I got it working with the code below:
row.onclick = (function() {
var details = notification;
return function() {
showModalJobDetails(details);
}
})();
Upvotes: 0
Reputation: 128991
Capture notification
as a parameter to an anonymous function. Since it looks like you’re using jQuery, you can use jQuery.each
, which will simplify your iteration and as a side effect capture it:
$.each(dataTable, function(index, notification) {
// ...
});
By the way, if you are using jQuery, you can write your code more concisely:
var row = $('<tr>').click(function() {
alert(notification.Name);
});
$('<td>').text(notification.Name).appendTo(row);
$('<td>').text(notification.State).appendTo(row);
$('<td>').text(notification.NotificationReceived ? 'Received' : 'Missing').appendTo(row);
row.appendTo('#' + notification.Client + '_TableJobDetails > ' +
'#' + notification.Client + notification.HostFormated + '_TableBodyJobDetails');
Further, if your IDs are unique (as they should be), you need not specify the whole hierarchy; just use
row.appendTo('#' + notification.Client + notification.HostFormated + '_TableBodyJobDetails');
Also, while it is a larger change in your code, consider using delegation with on
.
Upvotes: 1