Hi all,
I'm working on a button to rename files, removing all but the first n charachters of the file name. Since I didn't get anywhere using RegEx, I'm going for a script now.
This code works, albeit with a fixed number of characters:
[code]Rename PATTERN * TO * AUTORENAME
@script jscript
var len = 6
function OnGetNewName(data) {
if (len > 0) {
var stem = data.item.name_stem;
stem = stem.substr(0, len);
var newName = stem + data.item.ext;
return newName;
}
}
[/code]
Now I want to add a dialog for entering the number of characters. This value will apply to all files: I want the dialog to show only once, so I add it to the global section before the actual OnGetNewName() function:
[code]Rename PATTERN * TO * AUTORENAME
@script jscript
var len = -1
var dlg = DOpus.Dlg();
dlg.message = "Rename files, removing all but the first n characters.\nEnter number of characters:";
dlg.title = "Leave first charachters";
dlg.buttons = "&Rename|&Cancel";
dlg.icon = "question";
dlg.max = 3;
if (dlg.Show() > 0) {
len = parseInt(dlg.input);
}
function OnGetNewName(data) {
if (len > 0) {
var stem = data.item.name_stem;
stem = stem.substr(0, len);
var newName = stem + data.item.ext;
return newName;
}
}[/code]
The dialog works, but nothing happens afterwards: Apparently, the function is not called at all.
Is it not possible to add a dialog to a rename script like this?
Next, I tried adding the dialog to the OnGetNewName() function and running it only for the first file, using a global flag:
[code]Rename PATTERN * TO * AUTORENAME
@script jscript
var len = 0
var firstFile = true;
function OnGetNewName(data) {
if (firstFile) {
firstFile = false;
var dlg = DOpus.Dlg();
dlg.message = "Rename files, removing all but the first n characters.\nEnter number of characters:";
dlg.title = "Leave first charachters";
dlg.buttons = "&Rename|&Cancel";
dlg.icon = "question";
dlg.max = 3;
if (dlg.Show() > 0) {
len = parseInt(dlg.input);
len = isNaN(len) ? 0 : len;
}
}
if (len > 0) {
var stem = data.item.name_stem;
stem = stem.substr(0, len);
var newName = stem + data.item.ext;
return newName;
}
}
[/code]
That does what I need, but my question about the dialog before the function remains: What are the rules for the global part of the script?
Thanks,
MartO