Change text using a variable in InDesign javascript - javascript

I'm trying to find all "#"s on the active page and change them to numbers, ie. 1, 2, 3 . . .
The code below is what I thought would work but it doesn't. Instead, it changes every "#" to a "0".
app.findTextPreferences = app.changeTextPreferences = NothingEnum.NOTHING;
app.findTextPreferences.findWhat = "#";
var finds = app.activeDocument.findText();
if (finds.length > 0) {
for (var i = 0; i < finds.length; i++)
{
app.changeTextPreferences.changeTo = "no: " + i;
app.activeDocument.changeText();
}
else
{
alert("Nothing has been found");
}
}

As ali haydar stated, changeText will apply globally and will break the former findText texts references. What you need is to use the contents property in your loop.
app.findTextPreferences = app.changeTextPreferences = NothingEnum.NOTHING;
app.findTextPreferences.findWhat = "#";
var finds = app.activeDocument.findText();
if (finds.length > 0)
{
for (var i = 0; i < finds.length; i++)
{
finds[i].contents = "no: " + String(i);
}
}
else
{
alert("Nothing has been found");
}

In fact you can even get rid of the if condition:
app.findTextPreferences = app.changeTextPreferences = null;
app.findTextPreferences.findWhat = "#";
var finds = app.activeDocument.findText();
var n = finds.length;
var nStart = n;
while (n-- ) finds[n].contents = "no: " + String(n+1);
alert(nStart? nStart+" replacements made…" : "Nothing has been found");

To consider page 1 only…
var main = function(){
var doc = app.properties.activeDocument,
finds,n;
app.findTextPreferences = app.changeTextPreferences = null;
app.findTextPreferences.findWhat = "#";
if ( !doc ) return;
finds = doc.findText();
n = finds.length;
while (n-- ) {
finds[n].parentTextFrames.length
&& finds[n].parentTextFrames[0].isValid
&& finds[n].parentTextFrames[0].parentPage.id==doc.pages[0].id
&& finds[n].contents = "no: " + String(n+1);
}
};
main();

Related

Creating an array from a script then alert the contents

I've created a script to create a new array called spots, here is the script:
main();
function main() {
var doc = app.activeDocument;
var selectedSwatches = doc.swatches.getSelected();
var pageNumber = 1;
var count = 0;
if (selectedSwatches.length > 0) {
var text = 'var spots = new Array(\n';
for (var i = 0; i < selectedSwatches.length; i++) {
var swatch = selectedSwatches[i]
var color = swatch.color;
// Spot
if (color.typename == "SpotColor") {
count++;
text += '"' + color.spot.name + '", ' + "\n";
color = color.spot.color;
if (count % 10 == 0)
pageNumber++;
}
}
var textend = ');';
var textArray = text + textend;
alert(textArray);
} else {
alert("No Swatches Selected.");
}
}
This script alerts the following:
var spots = new Array(
"Yellow 012 C",
"Bright Red C",
);
How do I now alert the contents of that array i.e. Yellow 012 C, Bright Red C
I have tried using:
alert(spots);
But I get the error undefined maybe because the array is created on the fly and its not placed in the script?
UPDATE:
As per the comments, I have edited the script adding:
var spots = [];
spots.push(color.spot)
alert(spots);
I now get the following error: undefined is not an object
Here's the full script
main();
function main() {
var doc = app.activeDocument;
var selectedSwatches = doc.swatches.getSelected();
var pageNumber = 1;
var count = 0;
if (selectedSwatches.length > 0) {
var text = 'var spots = new Array(\n';
for (var i = 0; i < selectedSwatches.length; i++) {
var swatch = selectedSwatches[i]
var color = swatch.color;
// Spot
if (color.typename == "SpotColor") {
count++;
text += '"' + color.spot.name + '", ' + "\n";
color = color.spot.color;
if (count % 10 == 0)
pageNumber++;
}
}
var textend = ');';
var textArray = text + textend;
var spots = [];
spots.push(color.spot)
alert(spots);
} else {
alert("No Swatches Selected.");
}
}
Try
function main() {
//var doc = app.activeDocument;
var selectedSwatches
= [{"color":{"spot":{"color":"#ff0000","name":"red"},"typename":"SpotColor"}}
,{"color":{"spot":{"color":"#000000","name":"black"},"typename":"SpotColor"}}];
// = doc.swatches.getSelected();
var pageNumber = 1;
var count = 0;
var spots = [];
if (selectedSwatches.length > 0) {
for (var i = 0; i < selectedSwatches.length; i++) {
var swatch = selectedSwatches[i]
var color = swatch.color;
// Spot
if (color.typename == "SpotColor") {
count++;
spots.push(color.spot.name);
color = color.spot.color;
if (count % 10 == 0)
pageNumber++;
}
}
alert(spots.toString());
} else {
alert("No Swatches Selected.");
}
}
<button onclick="main()">Main</>

It always show either one output, either it highlight the keywords or only the alert box,how to achieve both at the same time

//grab all div elements in the pages;
let elt = document.getElementsByTagName("div");
var i;
var b = [];
b[0] = "password";
b[1] = "update";
b[2] = "account";
b[3] = "blocked";
b[4] = "alert";
b[5] = "confirm";
b[6] = "cash";
b[7] = "extra";
b[8] = "subscribe";
b[9] = "sample";
b[10] = "winner";
b[11] = "offer";
b[12] = "promotion";
b[13] = "urgent";
b[14] = "action";
b[15] = "update";
b[16] = "luxury";
b[17] = "limited";
b[18] = "login";
b[19] = "alert";
b[20] = "income";
b[21] = "bonus";
b[22] = "verify";
b[23] = "banking";
b[24] = "lowest";
b[25] = "deal";
b[26] = "unusual log in activity";
function scanDOM() {
//loop for html elements;
for (i = 0; i < elt.length; i++) {
var singleDiv = elt[i];
//loop for keywords;
for (j = 0; j < b.length; j++) {
var str = singleDiv.innerHTML;
if (str.indexOf(b[j]) > -1) {
//if found that the keywords match with the one in array, it will highlight the words;
str = str.replace(b[j], '<span style="background-color:#f6ff00;">' + b[j] + '</span>');
singleDiv.innerHTML = str;
popup();
}
}
}
}
// scan through the pages every 5 seconds;
setInterval(scanDOM, 5000);
//alert message;
function popup() {
alert * ("**WARNING!**");*
}

Upload a file to a web page as an attachment using VBA

I have a situation here. My company has a webpage which we use for ticket creation. The user gets the email and he has to create a ticket based on the info in the email. I tried to automate this process however got stuck at uploading the attachment.
When the user click on the attach button, a new pop up opens and my macro looses the control over the pop up.
So currently what am doing is,
Save the email - which needs to be attached.
Copy the path to clip board using a function
run a vb script to paste and enter using send keys with 5 seconds delay
click on the attach button.
So before the macro clicks the attach button, a VBS runs behind to paste and hit enter. So by the time the pop up opens VBS starts and closes the pop up.
I was checking to run the attach function within VB script so that I dont have to click on attach button. But I am not able to reach anywhere. anyone help?
The below are the functions available in the webpage. I dont know which one to run and how.
<script eval="true">/**
* Validate the attachments to see if at least
* one file is attached. Otherwise, show an alert.
*
* #returns {Boolean}
*/
function validateAttachment() {
var form = $('sys_attachment');
var fileFields = form.select('.attachmentRow');
for (var i = 0; i < fileFields.size(); i++) {
if (fileFields[i] && fileFields[i].value != "") {
setAttachButton(""); //disable
$('please_wait').style.display = "";
return true;
}
}
alert("Choose a file to attach");
return false;
}
/**
* Does the first attachment input field have a value?
* If not, use the grey button and change type of cursor.
* #param value
*/
function setDeleteButton(value) {
var field = $$('.attachmentRow')[0];
var text = field.select('input')[0];
var deleteButton = field.select('a.attachfile-delete img')[0];
if (!text.getValue().empty()) {
deleteButton.setAttribute('src', 'images/icons/kb_no.gif');
deleteButton.up().style.cursor = 'pointer';
} else {
deleteButton.setAttribute('src', 'images/icons/kb_no_disabled.gif');
deleteButton.up().style.cursor = 'default';
}
}
/**
* If the value passed in is an empty string,
* set the button to disabled state, otherwise
* enabled.
*
* #param value
*/
function setAttachButton(value) {
var attachButton = $("attachButton");
if (value == "")
attachButton.disabled = "true";
else
attachButton.disabled = "";
}
/**
* This controls the remove button for all attachments.
* If there are attachments in the list enable the button.
* Else keep disabled.
*
* #param e
*/
function setRemoveButton(e) {
var removeButton = gel("removeButton");
var deletedSysIdsElement = gel("deleted_sys_ids");
var deletedSysIds = new Array();
var deletedString = deletedSysIdsElement.value;
if (deletedString)
deletedSysIds = deletedString.split(";");
var thisId = e.name.substring(7);
if (e.checked) {
removeButton.disabled = "";
deletedSysIds.push(thisId);
} else {
var index = deletedSysIds.indexOf(thisId);
deletedSysIds.splice(index, 1);
// are there any left checked?
var inputs = document.getElementsByTagName("input");
var nonechecked = true;
var i = 0;
while(i < inputs.length && nonechecked) {
if (inputs[i].type == "checkbox" && inputs[i].name.substring(0, 7) == "sys_id_")
if (inputs[i].checked)
nonechecked = false;
i++;
}
if (nonechecked) {
removeButton.disabled = "true";
}
}
deletedSysIds = deletedSysIds.join(";");
deletedSysIdsElement.value = deletedSysIds;
}
function startRemoveAttachments() {
var removeButton = gel("removeButton");
removeButton.disabled = true;
gel('please_wait').style.display = "";
var thisUrl = gel("sysparm_this_url");
thisUrl.value = "attachment_deleted.do?sysparm_domain_restore=false&sysparm_nostack=yes&sysparm_deleted=" + gel("deleted_sys_ids").value;
return true;
}
/**
* Clear and Remove the attachment field that is
* passed in.
*
* #param field_id
*/
function clearAttachmentField(field) {
var form = $('sys_attachment');
var fileFields = form.select('.attachmentRow');
fileFields[0].setAttribute('data-position', 'first');
if (fileFields.size() > 1 && (field.readAttribute('data-position') != "first")) {
//check if field you are removing has a 3rd column (does it have an attach button?)
var needToAttachButton;
var attachButton = field.select('td')[2];
if (attachButton)
needToAttachButton = true;
//remove the field
field.remove();
//if you removed a field with a third column, add an attachbutton onto the new "first" field.
if (attachButton) {
var attachButton = new Element('input', {
"type": "submit",
"id": "attachButton",
"disabled": "true",
"value": "Attach" });
var td = new Element('td', {align: 'right'}).update(attachButton);
Element.extend(td);
form.select('.attachmentRow').first().select('td')[1].insert({'after': td});
}
}
else
clearFileField(field.select('td').first().select('input').first());
checkAndSetAttachButton();
}
/**
* Check all attachment input fields. If there is not attachment
* currently, disable the attachment button, else enable it.
*
* #returns
*/
function checkAndSetAttachButton() {
var form = $('sys_attachment');
var fileFields = form.select('.attachmentRow');
var validFileCount = 0;
for (var i = 0; i < fileFields.size(); i++) {
var field = fileFields[i].select('td').first().select('input').first();
if (field.getValue() != "") {
if (window.File && window.FileReader && window.FileList)
validFileCount += validateSizeandExt(field);
else
validFileCount += 1;
}
}
if (validFileCount == 0)
setAttachButton("");
else
setAttachButton("true");
}
function validateSizeandExt(field) {
var form = $('sys_attachment');
var maxSize = (form.max_size && form.max_size.value) ? form.max_size.value : 0;
var fileTypes = (form.file_types && form.file_types.value) ? form.file_types.value : "";
var files = field.files;
var allowedSize = maxSize * 1048576;
var warningString = "";
var checkJEXL = true;
for (var i = 0; i < files.length; i++) {
if (checkJEXL && isJEXLExpression(files[i].name)) {
warningString += files[i].name + " is an invalid file name.\n";
}
if (files[i].size > allowedSize && allowedSize != 0)
warningString += files[i].name + " is " + getDisplaySize(files[i].size) + ". The maximum file size is " + getDisplaySize(allowedSize) + ".\n";
if (!isValidFileType(files[i], fileTypes))
warningString += files[i].name + " has a prohibited file extension." + "\n";
}
if (warningString != "") {
alert(warningString);
clearFileField(field);
return 0;
}
return 1;
}
function isJEXLExpression(fileName) {
var phaseOneOpening = fileName.indexOf("$" + "{");
var phaseTwoOpening = fileName.indexOf("$" + "[");
if (phaseOneOpening != -1 || phaseTwoOpening != -1) {
return true;
}
return false;
}
function getDisplaySize(sizeInBytes) {
var kilobytes = Math.round(sizeInBytes / 1024);
if (kilobytes < 1)
kilobytes = 1;
var reportSize = kilobytes + "K";
if (kilobytes > 1024)
reportSize = Math.round(kilobytes / 1024) + "MB";
return reportSize;
}
function isValidFileType(file, types) {
var extensions = types || "";
if (extensions != "") {
extensions.toLowerCase();
extensions = extensions.split(",");
var periodIndex = file.name.lastIndexOf(".");
var extension = file.name.substring(periodIndex+1).toLowerCase();
if (extensions.indexOf(extension) == -1)
return false;
}
return true;
}
/**
* Clear a given field's contents.
*
* #param field
* the field element.
*/
function clearFileField(field) {
$(field).clear();
$(field).parentNode.innerHTML = $(field).parentNode.innerHTML;
checkAndSetAttachButton();
}
/**
* If the attachments are uploaded, clear any extra attachment input fields so
* they do not take up as much screen space. Additionally, clear the first field
* and keep it showing.
*/
function clearAttachmentFields() {
var form = $('sys_attachment');
var fileFields = form.select('.attachmentRow');
for (var i = 0; i < fileFields.size(); i++) {
if (i == 0)
clearFileField(fileFields[0].select('td').first().select('input').first());
if (i > 0)
fileFields[i].remove();
}
checkAndSetAttachButton();
setDeleteButton();
}
// this get called after an attachment is uploaded to update the display
function refreshAttachments(id, fileName, canDelete, createdBy, createdOn, contentType, encryption, iconPath) {
refreshLiveFeedAttachments(id, fileName, contentType, iconPath);
var encryptCheck = gel("encrypt_checkbox");
if (encryptCheck) {
encryptCheck.checked = false;
$('sysparm_encryption_context').value = "";
}
gel("please_wait").style.display = "none";
// if we didn't get an id, we could not read the attachment due to business rules so we're done
if (typeof id == "undefined")
return;
var noAttachments = gel("no_attachments");
if (noAttachments.style.display == "block")
noAttachments.style.display = "none";
// add the new upload to the display
var table = gel("attachment_table_body");
var tr = cel("tr");
var td = cel("td");
td.style.whiteSpace = "nowrap";
td.colspan = "2";
if (canDelete=="true") {
var input = cel("input");
var checkId = "sys_id_" + id;
input.name = checkId;
input.id = checkId;
input.type = "checkbox";
input.onclick = function() {setRemoveButton(gel(checkId));};
td.appendChild(input);
gel("delete_button_span").style.display = "inline";
var text = document.createTextNode(" ");
td.appendChild(text);
input = cel("input");
input.type = "hidden";
input.name = "Name";
input.value = "false";
td.appendChild(input);
}
var attachment_input = cel("input");
attachment_input.className = "attachment_sys_id";
attachment_input.type = "hidden";
attachment_input.id = id;
td.appendChild(attachment_input);
var anchor = cel("a");
anchor.style.marginRight = "4px";
anchor.href = "sys_attachment.do?sys_id=" + id;
anchor.title = "Attached by " + createdBy + " on " + createdOn;
var imgSrc = iconPath;
if (encryption != "") {
anchor.title += ", Encrypted: " + encryption;
imgSrc = "images/icons/attachment_encrypted.gifx";
}
var img = cel("img");
img.src = imgSrc;
img.alt = anchor.title;
anchor.appendChild(img);
var text = $(cel('a'));
getMessage("Download {0}", function(msg) {
text.setAttribute("aria-label", new GwtMessage().format(msg, fileName));
});
text.href = "sys_attachment.do?sys_id=" + id;
text.onkeydown = function(event){return allowInPlaceEditModification(text, event);};
text.style.marginRight = "5px";
text.style.maxWidth = "75%";
text.style.display = "inline-block";
text.style.overflow = "hidden";
text.style.verticalAlign = "middle";
if ('innerText' in text)
text.innerText = fileName;
else
text.textContent = fileName;
text.setAttribute("data-id", id);
text.inPlaceEdit({
selectOnStart: true,
turnClickEditingOff: true,
onBeforeEdit: function() {
text.lastAriaLabel = text.getAttribute("aria-label");
text.removeAttribute("aria-label");
text.setAttribute("role", "textbox");
},
onEditCancelled: function() {
text.removeAttribute("role");
if (text.lastAriaLabel) {
text.setAttribute("aria-label", text.lastAriaLabel);
}
},
onAfterEdit: function(newName) {
var oldName = this.oldValue;
var ga = new GlideAjax('AttachmentAjax');
ga.addParam('sysparm_type', 'rename');
ga.addParam('sysparm_value', id);
ga.addParam('sysparm_name', newName);
ga.getXML(function(response){
var answer = response.responseXML.documentElement.getAttribute("answer");
if (answer !== '0')
alert(new GwtMessage().getMessage("Renaming attachment {0} to new name {1} is not allowed", oldName, newName));
$$('a[data-id="' + id + '"]').each(function(elem){
if ('innerText' in elem)
elem.innerText = (answer === '0') ? newName : oldName;
else
elem.textContent = (answer === '0') ? newName : oldName;
});
$$('span[data-id="' + id + '"]').each(function(elem){
if ('innerText' in elem)
elem.innerText = (answer === '0') ? newName : oldName;
else
elem.textContent = (answer === '0') ? newName : oldName;
});
/*
This routine updates the attachment in the attachment modal AND the same attachment on the parent form
*/
getMessage(["Download {0}", "View {0}", "Rename {0}"], function(msg) {
var newDownloadText = new GwtMessage().format(msg["Download {0}"], newName);
var newViewText = new GwtMessage().format(msg["View {0}"], newName);
var newRenameText = new GwtMessage().format(msg["Rename {0}"], newName);
console.log(id)
$$('a[data-id="' + id + '"]').each(function(elem){
elem.setAttribute("aria-label", newDownloadText);
})
$$('.view_' + id).each(function(elem){
elem.setAttribute("aria-label", newViewText);
})
$$('.rename_' + id).each(function(elem){
elem.setAttribute("aria-label", newRenameText);
})
})
text.removeAttribute("role");
});
}
});
if (contentType == "text/html")
anchor.target = "_blank";
td.appendChild(anchor);
td.appendChild(text);
var allowRename = gel('ni.show_rename_link').value;
if (allowRename == "true") {
var renameAttachment = $(cel('a'));
renameAttachment.href = "#";
renameAttachment.setAttribute("role", "button");
getMessage("Rename {0}", function(msg) {
renameAttachment.setAttribute("aria-label", new GwtMessage().format(msg, fileName));
});
renameAttachment.className = 'attachment rename_' + id;
renameAttachment.onclick = function() {
text.beginEdit();
};
renameAttachment.innerHTML = '[rename]';
td.appendChild(renameAttachment);
}
var showView = gel("ni.show_attachment_view").value;
if (showView == "true") {
var blank = document.createTextNode(" ");
tr.appendChild(blank);
var view = cel("a");
view.href = "#";
getMessage("View {0}", function(msg) {
view.setAttribute("aria-label", new GwtMessage().format(msg, fileName));
});
var newText = document.createTextNode('[view]');
view.appendChild(newText);
view.className = "attachment view_" + id;
if (showPopup == "false")
view.href = "sys_attachment.do?sys_id=" + id + "&view=true";
else
view.onclick = function() {
tearOffAttachment(id)
};
td.appendChild(blank);
td.appendChild(view);
}
var showPopup = gel("ni.show_attachment_popup").value;
tr.appendChild(td);
table.appendChild(tr);
//If a new attachment is added check if attachments are marked for edge encryption before showing the Download all button
if (!edgeEncryptionEnabledForAttachments && hasAttachments()){
gel("download_all_button").style.display = "inline";
}
var form_table_id = "";
if(gel("sys_uniqueValue") || gel("sysparm_attachment_cart_id")){
form_table_id = (gel("sys_uniqueValue") || gel("sysparm_attachment_cart_id")).value;
}
if(form_table_id && attachmentParentSysId != form_table_id){
CustomEvent.fire('record.attachment.uploaded', {
sysid: id,
name: fileName,
hoverText: anchor.title,
image: imgSrc,
showRename: allowRename,
showView: showView,
showPopup: showPopup
});
}else{
addAttachmentNameToForm(id, fileName, anchor.title, imgSrc, allowRename, showView, showPopup);
}
if (g_accessibility)
alert(fileName + " " + anchor.title);
}
function refreshLiveFeedAttachments(sys_id, fileName, contentType, iconPath) {
var p = gel('live_feed_message_images');
if (!p)
return;
if (!contentType)
return;
if (contentType.indexOf('image') != 0 || contentType.indexOf('image/tif') == 0)
refreshLiveFeedNonImages(p, sys_id, iconPath, fileName);
else
refreshLiveFeedImages(p, sys_id, fileName);
var container = $('live_feed_image_container');
if (container)
container.show();
}
function refreshLiveFeedNonImages(p, sys_id, iconPath, fileName) {
var a = cel('a');
a.onclick = function() {tearOffAttachment(sys_id)};
a.title = fileName;
a.className = "live_feed_attachment_link";
var img = cel('img');
img.src = iconPath;
img.className = 'live_feed_image_thumbnail';
img.setAttribute("data-sys_id", sys_id);
a.appendChild(img);
var span = cel('span');
span.setAttribute('data-id', sys_id);
if ('innerText' in span)
span.innerText = fileName;
else
span.textContet = fileName;
a.appendChild(span);
p.appendChild(a);
p.appendChild(cel('br'));
setTimeout(this.hideLoading.bind(this), 200);
}
function refreshLiveFeedImages(p, sys_id, fileName) {
var imageName = "sys_attachment.do?sys_id=" + sys_id;
var a = cel('a');
a.onclick = function() {tearOffAttachment(sys_id)};
a.title = fileName;
a.className = "live_feed_attachment_link";
var img = cel('img');
img.src = imageName;
img.className = 'live_feed_image_thumbnail';
img.setAttribute("data-sys_id", sys_id);
a.appendChild(img);
p.appendChild(a);
p.appendChild(cel('br'));
setTimeout(this.hideLoading.bind(this), 200);
}
// this get called after attachments are deleted to update the display
function deletedAttachments(sysIds) {
var form_table_id = "";
if(gel("sys_uniqueValue") || gel("sysparm_attachment_cart_id")){
form_table_id = (gel("sys_uniqueValue") || gel("sysparm_attachment_cart_id")).value;
}
if(form_table_id && attachmentParentSysId != form_table_id){
CustomEvent.fire('record.attachment.deleted', sysIds);
return;
}
deleteLiveFeedAttachments(sysIds);
var modified = $("attachments_modified");
if (modified)
modified.value = "true";
var header_attachment = $('header_attachment');
gel("deleted_sys_ids").value = ""; // there should be none on the list once we return
var idArray = sysIds.split(";");
for (var i=0; i<idArray.length; i++) {
var id = idArray[i];
changeCount(attachmentParentSysId, 'decrease');
var e = gel("sys_id_" + id);
var tr = e.parentNode.parentNode;
rel(tr);
e = gel("attachment_" + id);
if (e)
rel(e);
}
var inputs = document.getElementsByTagName("input");
var anAttachment = false;
var i = 0;
while(i < inputs.length && !anAttachment) {
if (inputs[i].type == "checkbox" && inputs[i].name.substring(0, 7) == "sys_id_")
anAttachment = true;
i++;
}
if (!anAttachment) {
var noAttachments = gel("no_attachments");
noAttachments.style.display = "none";
var removeButton = gel("removeButton");
removeButton.disabled = true;
var downloadAllButton = gel("download_all_button");
downloadAllButton.style.display = "none";
gel('delete_button_span').style.display = "none";
hideObject($("header_attachment_list_label"));
if (header_attachment)
header_attachment.style.height = "auto";
var line = $("header_attachment_line");
if (line) {
line.style.visibility = "hidden";
line.style.display = "none";
}
}
gel("please_wait").style.display = "none";
var more_attachments = $('more_attachments');
if (more_attachments && header_attachment)
if( (computeAttachmentWidth() - 20) >= (header_attachment.getWidth() - more_attachments.getWidth()))
more_attachments.style.display = 'block';
else
more_attachments.style.display = 'none';
}
function deleteLiveFeedAttachments(sysIds) {
var p = $('live_feed_message_images');
if (!p)
return;
if (!p.visible())
return;
idArray = sysIds.split(";");
for (var i=0; i<idArray.length; i++) {
var imgs = p.select("img.live_feed_image_thumbnail");
if (imgs.length < 1)
return;
for (var j=0; j<imgs.length; j++) {
if (imgs[j].getAttribute("data-sys_id") == idArray[i]) {
var elem = imgs[j].up("a.live_feed_attachment_link");
elem.remove();
if (elem.next() && (elem.next().tagName.toLowerCase() == "br"))
elem.next().remove();
}
}
}
if (p.select("img.live_feed_image_thumbnail").length > 0)
return;
var container = $('live_feed_image_container');
if (container)
container.hide();
}
function computeAttachmentWidth() {
var temp = $('header_attachment_list').select('li');
var totalWidth = 0;
for (var i = 0; i < temp.length; i++) {
totalWidth += temp[i].getWidth();
}
return totalWidth;
}
function closeAttachmentWindow() {
GlideModal.prototype.get('attachment').destroy();
}
/**
* Add an input field to the file browser in the dialog.
* This is called when the "Add Another Attachment" button
* is clicked.
* */
function addRowToTable() {
var formRows = $('sys_attachment').select(".attachmentRow");
var input = "<input type='file' title='Attach' " +
"name='attachFile' onchange='checkAndSetAttachButton(); setDeleteButton(this.value);'" +
"size=41 multiple=true />";
var img = "<a href='#' onclick='clearAttachmentField($(this).up().up()); setDeleteButton(this.value);'>" +
"<img src='images/icons/kb_no.gif'/></a>";
var row = "<tr class='attachmentRow'><td> "
+ input + "</td><td align='right'>" + img + "</td></tr>";
formRows.last().insert({ "after" : row });
}
/**
* Download all attachments
*/
function downloadAllAttachments(){
var downloadUrl = window.location.protocol + '//' + window.location.host + '/download_all_attachments.do?sysparm_sys_id=' + attachmentParentSysId;
window.location = downloadUrl;
}
function hasAttachments(){
return document.getElementsByClassName("attachment_sys_id").length > 0;
}</script>
This is what happens when I click on the attach button in the HTML. attachFile is the ID which I am using in my code to run.
<tr class="attachmentRow">
<td id="attachFileCell" colspan="3">
<input name="attachFile" title="" id="attachFile" onchange="checkAndSetAttachButton(); setDeleteButton(this.value); $('attachButton').click();" type="file" size="41" multiple="true" data-original-title="Attach">
<a class="attachfile-delete" style="display: none; cursor: default;" onclick="clearAttachmentField($(this).up().up()); setDeleteButton(this.value);" href="#">
<img src="images/icons/kb_no_disabled.gif">
</a>
<input disabled="" class="attachfile-attach button" id="attachButton" style="display: none;" type="submit" value="Attach">
</td>
</tr>
This is my VBA Code which I used.
Set IE = New SHDocVw.InternetExplorer
IE.Visible = True
IE.Navigate "https://sorry cant share the link as per the company policy"
Do While IE.Busy = True Or IE.READYSTATE <> 4: DoEvents: Loop
Set HTMLDoc = IE.Document
'***************** Save Email
eachitem.SaveAs StrFile, 3
'***************** file link to clipboard
CopyText StrFile
'***************** Attach Email
HTMLDoc.getElementById("header_add_attachment").Click
Application.Wait (Now() + TimeValue("00:00:02"))
'***************** Call external VBS file to handle the pop up then attach
Shell "Explorer.exe " & StrFolderPath & "SNOW.vbs", vbNormalFocus
HTMLDoc.getElementById("attachFile").Click
SendKeys "{Enter}", True
I tried the below method to call the function, but reaching nowhere! Any assistance would be appreciated. I really dont know which function attaches the file to the website and how.
Set HTMLDoc1 = IE.Document.parentWindow
HTMLDoc1.execScript code:="isJEXLExpression(" & StrFile & ")"
HTMLDoc1.execScript code:="checkAndSetAttachButton()"
HTMLDoc1.execScript code:="setDeleteButton(this.value)"
HTMLDoc1.execScript code:="$('attachButton').click()"
HTMLDoc1.execScript code:="clearAttachmentField($(this).up().up()); setDeleteButton(this.value);"

Javascript error after upgrade to Drupal 7

I posted a similar question at the Drupal Forum, but I haven't had much luck.
I'm upgrading a site from D6 to D7. So far it's gone well, but I'm getting a Javascript error that I just can't pin down a solution for.
This is a cut down version of the whole script:
(function($) {
function sign(secret, message) {
var messageBytes = str2binb(message);
var secretBytes = str2binb(secret);
if (secretBytes.length > 16) {
secretBytes = core_sha256(secretBytes, secret.length * chrsz);
}
var ipad = Array(16), opad = Array(16);
for (var i = 0; i < 16; i++) {
ipad[i] = secretBytes[i] ^ 0x36363636;
opad[i] = secretBytes[i] ^ 0x5C5C5C5C;
}
var imsg = ipad.concat(messageBytes);
var ihash = core_sha256(imsg, 512 + message.length * chrsz);
var omsg = opad.concat(ihash);
var ohash = core_sha256(omsg, 512 + 256);
var b64hash = binb2b64(ohash);
var urlhash = encodeURIComponent(b64hash);
return urlhash;
}
function addZero(n) {
return ( n < 0 || n > 9 ? "" : "0" ) + n;
}
Date.prototype.toISODate =
new Function("with (this)\nreturn " +
"getFullYear()+'-'+addZero(getMonth()+1)+'-'" +
"+addZero(getDate())+'T'+addZero(getHours())+':'" +
"+addZero(getMinutes())+':'+addZero(getSeconds())+'.000Z'");
function getNowTimeStamp() {
var time = new Date();
var gmtTime = new Date(time.getTime() + (time.getTimezoneOffset() * 60000));
return gmtTime.toISODate() ;
}
}(jQuery));
The part that keeps throwing an error I'm seeing in Firebug is at:
Date.prototype.toISODate =
new Function("with (this)\n return " +
"getFullYear()+'-'+addZero(getMonth()+1)+'-'" +
"+addZero(getDate())+'T'+addZero(getHours())+':'" +
"+addZero(getMinutes())+':'+addZero(getSeconds())+'.000Z'");
Firebug keeps stopping at "addZero is not defined". JS has never been my strong point, and I know some changes have been made in D7. I've already wrapped the entire script in "(function($) { }(jQuery));", but I must be missing something else. The same script works perfectly on the D6 site.
Here is the "fixed" version of the whole code with #Pointy suggestion added. All I left out is the part of the script for making the hash that goes to Amazon, and some of my declared variables.
(function($) {
var typedText;
var strSearch = /asin:/;
var srchASIN;
$(document).ready(function() {
$("#edit-field-game-title-und-0-asin").change(function() {
typedText = $("#edit-field-game-title-und-0-asin").val();
$.ajax({
type: 'POST',
data: {typedText: typedText},
dataType: 'text',
url: '/asin/autocomplete/',
success:function(){
document.getElementById('asin-lookup').style.display='none';
x = typedText.search(strSearch);
y = (x+5);
srchASIN = typedText.substr(y,10)
amazonSearch();
}
});
});
$("#search_asin").click(function() {
$("#edit-field-game-title-und-0-asin").val('');
document.getElementById('name-lookup').style.display='none';
$("#edit-field-game-title-und-0-asin").val('');
$("#edit-title").val('');
$("#edit-field-subtitle-und-0-value").val('');
$("#edit-field-game-edition-und-0-value").val('');
$("#edit-field-release-date-und-0-value-date").val('');
$("#edit-field-asin-und-0-asin").val('');
$("#edit-field-ean-und-0-value").val('');
$("#edit-field-amazon-results-und-0-value").val('');
$("#edit-body").val('');
srchASIN = $("#field-asin-enter").val();
amazonSearch();
});
$("#clear_search").click(function() {
$("#field-asin-enter").val('');
$("#edit-field-game-title-und-0-asin").val('');
$("#edit-title").val('');
$("#edit-field-subtitle-und-0-value").val('');
$("#edit-field-game-edition-und-0-value").val('');
$("#edit-field-release-date-und-0-value-date").val('');
$("#edit-field-release-dt2-und-0-value-date").val('');
$("#edit-field-asin-und-0-asin").val('');
$("#edit-field-ean-und-0-value").val('');
$("#edit-field-amazon-results-und-0-value").val('');
$("#field-amazon-platform").val('');
$("#field-amazon-esrb").val('');
$("#edit-body-und-0-value").val('');
document.getElementById('asin-lookup').style.display='';
document.getElementById('name-lookup').style.display='';
});
function amazonSearch(){
var ASIN = srchASIN;
var azScr = cel("script");
azScr.setAttribute("type", "text/javascript");
var requestUrl = invokeRequest(ASIN);
azScr.setAttribute("src", requestUrl);
document.getElementsByTagName("head").item(0).appendChild(azScr);
}
});
var amzJSONCallback = function(tmpData){
if(tmpData.Item){
var tmpItem = tmpData.Item;
}
$("#edit-title").val(tmpItem.title);
$("#edit-field-game-edition-und-0-value").val(tmpItem.edition);
$("#edit-field-release-date-und-0-value-date").val(tmpItem.relesdate);
$("#edit-field-release-dt2-und-0-value-date").val(tmpItem.relesdate);
$("#edit-field-asin-und-0-asin").val(tmpItem.asin);
$("#edit-field-ean-und-0-value").val(tmpItem.ean);
$("#field-amazon-platform").val(tmpItem.platform);
$("#field-amazon-publisher").val(tmpItem.publisher);
$("#field-amazon-esrb").val(tmpItem.esrb);
};
function ctn(x){ return document.createTextNode(x); }
function cel(x){ return document.createElement(x); }
function addEvent(obj,type,fn){
if (obj.addEventListener){obj.addEventListener(type,fn,false);}
else if (obj.attachEvent){obj["e"+type+fn]=fn; obj.attachEvent("on"+type,function(){obj["e"+type+fn]();});}
}
var styleXSL = "http://www.tlthost.net/sites/vglAmazonAsin.xsl";
function invokeRequest(ASIN) {
cleanASIN = ASIN.replace(/[-' ']/g,'');
var unsignedUrl = "http://xml-us.amznxslt.com/onca/xml?Service=AWSECommerceService&AssociateTag=theliterarytimes&IdType=ASIN&ItemId="+cleanASIN+"&Operation=ItemLookup&ResponseGroup=Medium,ItemAttributes,OfferFull&Style="+styleXSL+"&ContentType=text/javascript&CallBack=amzJSONCallback";
var lines = unsignedUrl.split("\n");
unsignedUrl = "";
for (var i in lines) { unsignedUrl += lines[i]; }
// find host and query portions
var urlregex = new RegExp("^http:\\/\\/(.*)\\/onca\\/xml\\?(.*)$");
var matches = urlregex.exec(unsignedUrl);
var host = matches[1].toLowerCase();
var query = matches[2];
// split the query into its constituent parts
var pairs = query.split("&");
// remove signature if already there
// remove access key id if already present
// and replace with the one user provided above
// add timestamp if not already present
pairs = cleanupRequest(pairs);
// encode the name and value in each pair
pairs = encodeNameValuePairs(pairs);
// sort them and put them back together to get the canonical query string
pairs.sort();
var canonicalQuery = pairs.join("&");
var stringToSign = "GET\n" + host + "\n/onca/xml\n" + canonicalQuery;
// calculate the signature
//var secret = getSecretAccessKey();
var signature = sign(secret, stringToSign);
// assemble the signed url
var signedUrl = "http://" + host + "/onca/xml?" + canonicalQuery + "&Signature=" + signature;
//document.write ("<html><body><pre>REQUEST: "+signedUrl+"</pre></body></html>");
return signedUrl;
}
function encodeNameValuePairs(pairs) {
for (var i = 0; i < pairs.length; i++) {
var name = "";
var value = "";
var pair = pairs[i];
var index = pair.indexOf("=");
// take care of special cases like "&foo&", "&foo=&" and "&=foo&"
if (index == -1) {
name = pair;
} else if (index == 0) {
value = pair;
} else {
name = pair.substring(0, index);
if (index < pair.length - 1) {
value = pair.substring(index + 1);
}
}
// decode and encode to make sure we undo any incorrect encoding
name = encodeURIComponent(decodeURIComponent(name));
value = value.replace(/\+/g, "%20");
value = encodeURIComponent(decodeURIComponent(value));
pairs[i] = name + "=" + value;
}
return pairs;
}
function cleanupRequest(pairs) {
var haveTimestamp = false;
var haveAwsId = false;
var nPairs = pairs.length;
var i = 0;
while (i < nPairs) {
var p = pairs[i];
if (p.search(/^Timestamp=/) != -1) {
haveTimestamp = true;
} else if (p.search(/^(AWSAccessKeyId|SubscriptionId)=/) != -1) {
pairs.splice(i, 1, "AWSAccessKeyId=" + accessKeyId);
haveAwsId = true;
} else if (p.search(/^Signature=/) != -1) {
pairs.splice(i, 1);
i--;
nPairs--;
}
i++;
}
if (!haveTimestamp) {
pairs.push("Timestamp=" + getNowTimeStamp());
}
if (!haveAwsId) {
pairs.push("AWSAccessKeyId=" + accessKeyId);
}
return pairs;
}
function sign(secret, message) {
var messageBytes = str2binb(message);
var secretBytes = str2binb(secret);
if (secretBytes.length > 16) {
secretBytes = core_sha256(secretBytes, secret.length * chrsz);
}
var ipad = Array(16), opad = Array(16);
for (var i = 0; i < 16; i++) {
ipad[i] = secretBytes[i] ^ 0x36363636;
opad[i] = secretBytes[i] ^ 0x5C5C5C5C;
}
var imsg = ipad.concat(messageBytes);
var ihash = core_sha256(imsg, 512 + message.length * chrsz);
var omsg = opad.concat(ihash);
var ohash = core_sha256(omsg, 512 + 256);
var b64hash = binb2b64(ohash);
var urlhash = encodeURIComponent(b64hash);
return urlhash;
}
Date.prototype.toISODate = function() {
function addZero(n) {
return ( n < 0 || n > 9 ? "" : "0" ) + n;
}
var d = this;
return d.getFullYear() + '-' +
addZero(d.getMonth() + 1) + '-' +
addZero(d.getDate()) + 'T' +
addZero(d.getHours()) + ':' +
addZero(d.getMinutes()) + ':' +
addZero(d.getSeconds()) + '.000Z';
};
function getNowTimeStamp() {
var time = new Date();
var gmtTime = new Date(time.getTime() + (time.getTimezoneOffset() * 60000));
return gmtTime.toISODate() ;
}
}(jQuery));
Here's a better version of your code:
Date.prototype.toISODate = function() {
function addZero(n) {
return ( n < 0 || n > 9 ? "" : "0" ) + n;
}
var d = this;
return d.getFullYear() + '-' +
addZero(d.getMonth() + 1) + '-' +
addZero(d.getDate()) + 'T' +
addZero(d.getHours()) + ':' +
addZero(d.getMinutes()) + ':' +
addZero(d.getSeconds()) + '.000Z';
};
That moves "addDate" inside the extension function, and it avoids the horrid with statement.

getElementById Another Question

As an extension question that Felix Kling answered so brilliantly I now need to do a two part check on the data table deployed.
Can anyone tell me how to add to the code below to allow me not only to copy the values of the pcode fields into an array but to check if there is a check in the checkbox with a corresponding row number i.e. route2 is check then add to the array but if route3 is not checked then exclude it.
function GetRoute()
{
var from = document.getElementById('inpAddr').value;
var locations = [from];
for(var i = 2; i <= 400; i++) {
var element = document.getElementById('pcode' + i);
if(element === null) { break; }
locations.push(element.innerHTML);
}
var options = new VERouteOptions();
options.DrawRoute = true;
options.RouteColor = new VEColor(63,160,222,1);
options.RouteWeight = 3;
options.RouteCallback = onGotRoute;
options.SetBestMapView = true;
options.DistanceUnit = VERouteDistanceUnit.Mile;
options.ShowDisambiguation = true;
map.GetDirections(locations,options);
}
Thanks in advance!
Justin
for( var i = 2 ; (element = document.getElementById('pcode' + i)) && i <= 400; i++ )
{
if( document.getElementById('route' + i).checked )
{
locations.push( element.innerHTML );
}
}
function GetRoute() {
var from = document.getElementById('inpAddr').value;
var locations = [from];
// My Modification Starts Here....
var maxLoopValue = 400;
var pcode, currentRoute, nextRoute;
for(var i = 2; i <= maxLoopValue; i++) {
pcode = document.getElementById('pcode' + i);
currentRoute = document.getElementById('route' + i);
// Make sure the currentRoute is 'checked'
if (currentRoute.checked) {
// Make sure there is a 'next' route before trying to check it
if (i < maxLoopValue) {
nextRoute = document.getElementById('route' + (i+1));
// Make sure the 'next' route is 'checked'
if (nextRoute.checked) {
locations.push(element.innerHTML);
}
} else {
// This is the last route, since we know it's checked, include it
locations.push(element.innerHTML);
}
}
}
// My Modification Ends Here....
var options = new VERouteOptions();
options.DrawRoute = true;
options.RouteColor = new VEColor(63,160,222,1);
options.RouteWeight = 3;
options.RouteCallback = onGotRoute;
options.SetBestMapView = true;
options.DistanceUnit = VERouteDistanceUnit.Mile;
options.ShowDisambiguation = true;
map.GetDirections(locations,options);
}

Categories