I have some working code which I'm trying to optimize using a loop but am having trouble concatenating the name of a parameter.
var objlocations = {};
$.get('https://example.com/something/ajax-state?somevar=' + somevar, function(data) {
$.each(data, function(index,DBRow){
objlocations['point1x'] = DBRow.Point01X;
objlocations['point1y'] = DBRow.Point01Y;
objlocations['point2x'] = DBRow.Point02X;
objlocations['point2y'] = DBRow.Point02Y;
objlocations['point3x'] = DBRow.Point03X;
objlocations['point3y'] = DBRow.Point03Y;
objlocations['point4x'] = DBRow.Point04X;
objlocations['point4y'] = DBRow.Point04Y;
// There are about 30 more of these needed
var $grid = jQuery('#MyDiv');
$grid.empty();
for(var i=1;i<=4;i++) {
var x = objlocations['point' + i + 'x'];
var y = objlocations['point' + i + 'y'];
// doesnt' work: var x = 'DBRow.Point0'+i+'X';
// doesn't work: var y = 'DBRow.Point0'+i+'Y';
var $PointLocation = jQuery('<img class="PointLocation" id="Grid-Point-' + i + '"' + 'src="../img/points/point.png" width="50px">').css({top:y + 'px', left:x + 'px'});
$grid.append($PointLocation);
}
});
});
For the variables "x" and "y" I'd like to loop through and directly use DBRow.PointxX rather than first manually dumping them into an object since there will be over 60 lines required.
As per the comment in the code I've tried var x = 'DBRow.Point0'+i+'X' which results in "x" having "DBRow.Point01X" etc as a string value.
If I try without the quotes like this: DBRow.Point0+i+X I get a console error stating that X is not defined.
I'll also have to do something about the leading 0 on the DBRow.Point##X but I may be able to do this in the database I'm pulling from.
I'm new to Javascript so hopefully this is something simple that I'm overlooking.
Edit: Final solution
$.get('https://example.com/something/ajax-state?somevar=' + somevar, function(data) {
$.each(data, function(index,DBRow){
var $grid = jQuery('#MyDiv');
$grid.empty();
for(var i=1;i<=32;i++) {
var ii = ('00'+i).slice(-2);
var x = DBRow["Point"+ii+"X"];
var y = DBRow["Point"+ii+"Y"];
var $PointLocation = jQuery('<img class="PointLocation" id="Grid-Point-' + i + '"' + 'src="../img/points/point.png" width="50px">').css({top:y + 'px', left:x + 'px'});
$grid.append($PointLocation);
}
});
});