Copy link to clipboard
Copied
Hi community, good afternoon, can anybody help me with this code?
I am trying to get the value of the selected button, I am using icon buttons because I need to show in the UI how is the color, however when I try to get the value or the position of [i] in which is selected for some reason it always returns the number "11". I have 33 images in the folder and I split it in three columns so I dont have a large UI to pick (it is too big hehe)
I'll appreciate any help or suggestions:
var dir = Folder("C:\\Users\\USER\\Downloads\\Colors");
var files = dir.getFiles("*.png");
var w= new Window("dialog");
w.orientation= "row";
var seleccion = "";
var firstcolumn = w.add ("panel");
var secondcolumn = w.add ("panel");
var thirdcolumn = w.add ("panel");
firstcolumn.orientation = "column";
secondcolumn.orientation = "column";
thirdcolumn.orientation = "column";
for(var f = 0; f < files.length; f++){
while (f<11) {
firstcolumn.add ("iconbutton", undefined, files[f], {name: i, style: "toolbutton"});
f++;
}
while (f<22) {
secondcolumn.add ("iconbutton", undefined, files[f], {name: i, style: "toolbutton"});
f++;
}
thirdcolumn.add ("iconbutton", undefined, files[f], {name: i, style: "toolbutton"});
}
//Create button.
var botones = w.add("group");
// botones.orientation = "row";
botones.add ("button", undefined, "OK");
for (var i = 0; i < firstcolumn.children.length; i++) {
firstcolumn.children[i].onClick = function(){
alert(this.name);
}
}
// w.show ();
if(w.show() == 1){
alert(seleccion);
}
Your problem is in this
for (var i = 0; i < firstcolumn.children.length; i++) {
firstcolumn.children[i].onClick = function(){
// alert(this.name);
// alert(i);
}
}
With each iteration, the preceding i in onClick is overridden by the present i. So by the time the window is shown, i will always be the last iteration, i.e. 11.
Keep i in scope as follows
for (var i = 0; i < firstcolumn.children.length; i++) {
(function (i) {
firstcolumn.children[i].onClick = funct
...
Copy link to clipboard
Copied
Your problem is in this
for (var i = 0; i < firstcolumn.children.length; i++) {
firstcolumn.children[i].onClick = function(){
// alert(this.name);
// alert(i);
}
}
With each iteration, the preceding i in onClick is overridden by the present i. So by the time the window is shown, i will always be the last iteration, i.e. 11.
Keep i in scope as follows
for (var i = 0; i < firstcolumn.children.length; i++) {
(function (i) {
firstcolumn.children[i].onClick = function(){
alert(i);
};
})(i);
}
Copy link to clipboard
Copied
Amazing! I did not see that part about the iteration, here is the part of the code completed with yours:
for (var i = 0; i < firstcolumn.children.length; i++) {
(function (i) {
firstcolumn.children[i].onClick = function(){
MySelectedColor = i;
MySelectedColumn = "firstcolumn"
};
})(i);
}
I added MySelectedColor and MySelectedColumn in order to locate which iconbutton was selected from which panel. Thank you so much.