I'm struggling with dynamic generation of buttons over a JSON array.
Stripped-down code is this (aim is to build a table based on the data, nothing fancy yet, I'm not yet proficient at this):
$.ajax({
/* type, content, etc. removed */
success: function (data, textStatus, XmlHttpRequest) {
var target = $('myContainerDiv');
var result = data.d.results;
var $table = $('<table />');
for(var i=0;i < results.length; i++) {
var $row = $('<tr />');
var $cell = $('<td />');
var $button = $('<input />').attr({ type: 'button', value: 'Edit', name: 'btn' + i });
$button.click(function () {
// **
// In a .NET environment, this would become a closure
// I suspect this is the offending bit of code
//
alert(results[i].name);
};
$cell.append($button);
$row.append($cell);
$table.append($row);
}
$target.append($table);
},
/* error etc. removed*/
});
I basically want a column filled with buttons, each one would popup the value of a field from the array I get from my $.ajax
call.
Buttons actually show up, but they do not react to clicking, and I see no runtime error in the F12 tools console. This is probably due to the fact that this script is part of the configuration page for a Microsoft Dynamics CRM 2011 Solution, but other than that, I'm sure the AJAX call goes on OK (I tried making it print out data, and I can see it).
UPDATE
Referencing i
inside the click handler was the offending line indeed: changed the code like this made things work as I was expecting:
var $button = $('<input />').attr({ type: 'button', value: 'Edit', name: 'btn' + results[i].name });
$button.click(function () {
// 'i' value is NOT what I thought it was !
alert(this.name.substring(3,this.name.length));
// I found out in the meanwhile that 'this' references the event source
};
First you have several syntax errors in your code and it may not be running at all:
if the ID of your div container is myContainerDiv
, to get the target you need to do $('#myContainerDiv')
you create a result
varialbe, but you use a results
variable
you're not closing the parentesis in the $button.click
you're adding everything to $target
but is defined as target
Now the actual problem may be, as you say, the closure, remember that you close over variables not values, so when you execute the button click handler, i
has a value of results.length
, so you are out of bounds by that time.
You could try to store the results
objects elsewhere, extract the Id of the object your looking for from the button (you're naming then 'btn'+i
) and then access the name
property that way.