I'm in trouble with saving a word in Javascript ! I want to save the document as "x" by concatenating several vars.
I tried the following:
<script>// SAVE AS WORD
var fname = document.getElementsByName("fname")[0].value;
var name = document.getElementsByName("name")[0].value;
var company = <?php echo json_encode($company); ?>;
function exportHTML(){
var header = "<html xmlns:o='urn:schemas-microsoft-com:office:office' "+
"xmlns:w='urn:schemas-microsoft-com:office:word' "+
"xmlns='http://www.w3.org/TR/REC-html40'>"+
"<head><meta charset='utf-8'><title>Export HTML to Word Document with JavaScript</title></head><body>";
var footer = "</body></html>";
var sourceHTML = header+document.getElementById("pdf").innerHTML+footer;
var source = 'data:application/vnd.ms-word;charset=utf-8,' + encodeURIComponent(sourceHTML);
var fileDownload = document.createElement("a");
document.body.appendChild(fileDownload);
fileDownload.href = source;
**fileDownload.download = concat(fname,'-',name,'-LM-',company,'.doc');**
fileDownload.click();
document.body.removeChild(fileDownload);
}
</script>
The save-as line is the following :
**fileDownload.download = concat(fname,'-',name,'-LM-',company,'.doc');**
Any idea ? Thanks a lot from France !
concat is a method of String.prototype, so use it like this:
fileDownload.download = fname.concat('-', name, '-LM-', company, '.doc')
Or you can use the concatenation operator + :
fileDownload.download = fname + '-' + name + '-LM-' + company + '.doc';
Or you can use template strings:
fileDownload.download = `${fname}-${name}-LM-${company}.doc`;
Related
I have written a script which has a trigger to run every hour, it searches my emails and extracts the data, turns it to a PDF and locates it in a folder if the subject equals "xxxx", it overwrites data in the folder if it already exists.. I would like to add in a new if function where it will only pick up emails for the current day and not history (to save efficiency of the script and data)
function saveGmailAsPDF2() {
var gmailLabels = 'xxxxx';
var driveFolder = DriveApp.getFolderById("folder url");
var threads = GmailApp.search("subject:" + gmailLabels,0,20);
if (threads.length > 0) {
/* Google Drive folder where the Files would be saved */
var folders = DriveApp.getFoldersByName(driveFolder);
var folder = folders.hasNext() ?
folders.next() : DriveApp.createFolder(driveFolder);
/* Gmail Label that contains the queue */
var label = GmailApp.getUserLabelByName(gmailLabels) ?
GmailApp.getUserLabelByName(gmailLabels) : GmailApp.createLabel(driveFolder);
for (var t=0; t<threads.length; t++) {
threads[t].removeLabel(label);
var msgs = threads[t].getMessages();
var html = "";
var subject = threads[t].getFirstMessageSubject();
var previousdoc = driveFolder.getFilesByName(subject + ".pdf"); //gets name of csv, if exists in drive then move to trash before creating new file
if (previousdoc.hasNext()) {
previousdoc.next().setTrashed(true);}
/* Append all the threads in a message in an HTML document */
for (var m=0; m<msgs.length; m++) {
var msg = msgs[m];
html += "From: " + msg.getFrom() + "<br />";
html += "To: " + msg.getTo() + "<br />";
html += "Date: " + msg.getDate() + "<br />";
html += "Subject: " + msg.getSubject() + "<br />";
html += "<hr />";
html += msg.getBody().replace(/<img[^>]*>/g,"");
html += "<hr />";}
/* Convert the Email Thread into a PDF File */
var tempFile = DriveApp.createFile("temp.html", html, "text/html");
folder.createFile(tempFile.getAs("application/pdf")).setName(subject + ".pdf");
tempFile.setTrashed(true);}}}
Explanation:
There is a function getLastMessageDate() that gives the date of a thread's most recent message. You can compare that against the date of today and if they match execute the rest of the code.
Since you use a for loop: for (var t=0; t<threads.length; t++)
I think the condition if (threads.length > 0) is redundant because for loop won't run anyway if threads.length equals 0.
Because of the latter, I transferred the folder creation part of your code into the loop itself and execute it only when the last day of the thread is equal to today. But I leave this part for you to decide.
I can't test your code but this should work:
function saveGmailAsPDF2() {
var gmailLabels = 'xxxxx';
var driveFolder = DriveApp.getFolderById("folder url");
var threads = GmailApp.search("subject:" + gmailLabels,0,20);
// new code
const today = new Date();
const ss = SpreadsheetApp.getActive();
const timezone = ss.getSpreadsheetTimeZone();
const today_dt = Utilities.formatDate(today, timezone, 'yyyy-MM-dd');
///////////
for (var t=0; t<threads.length; t++) {
// new code
var lastMessageDate = threads[t].getLastMessageDate();
var thread_dt = Utilities.formatDate(lastMessageDate, timezone, 'yyyy-MM-dd');
if(today_dt==thread_dt){
///////////
/* Google Drive folder where the Files would be saved */
var folders = DriveApp.getFoldersByName(driveFolder);
var folder = folders.hasNext() ?
folders.next() : DriveApp.createFolder(driveFolder);
/* Gmail Label that contains the queue */
var label = GmailApp.getUserLabelByName(gmailLabels) ?
GmailApp.getUserLabelByName(gmailLabels) : GmailApp.createLabel(driveFolder);
threads[t].removeLabel(label);
var msgs = threads[t].getMessages();
var html = "";
var subject = threads[t].getFirstMessageSubject();
var previousdoc = driveFolder.getFilesByName(subject + ".pdf"); //gets name of csv, if exists in drive then move to trash before creating new file
if (previousdoc.hasNext()) {
previousdoc.next().setTrashed(true);}
/* Append all the threads in a message in an HTML document */
for (var m=0; m<msgs.length; m++) {
var msg = msgs[m];
html += "From: " + msg.getFrom() + "<br />";
html += "To: " + msg.getTo() + "<br />";
html += "Date: " + msg.getDate() + "<br />";
html += "Subject: " + msg.getSubject() + "<br />";
html += "<hr />";
html += msg.getBody().replace(/<img[^>]*>/g,"");
html += "<hr />";}
/* Convert the Email Thread into a PDF File */
var tempFile = DriveApp.createFile("temp.html", html, "text/html");
folder.createFile(tempFile.getAs("application/pdf")).setName(subject + ".pdf");
tempFile.setTrashed(true);}}}
i have a button when i click on this button then whatsapp opens and when i click in a chat and want to send massege then all things come properly but full url not come because & included in my url.
My Url is like this
www.yoururl.com?1st=1&2nd=2&3rd=2&4th=1&5th=2&6th=2&7th=2&8th=2&9th=2&10th=2&share=share&name=s
But sharing in whatsapp then comes only
www.yoururl.com?1st=1
when i remove first & Then url is comes
www.yoururl.com?1st=12nd=2
so i want to share full url with &
Here Is javascript code Code
var url1 = "?1st=" + encodeURIComponent(selectedOption1) + "&2nd=" + encodeURIComponent(selectedOption2) + "&3rd=" + encodeURIComponent(selectedOption3) + "&4th=" + encodeURIComponent(selectedOption4) + "&5th=" + encodeURIComponent(selectedOption5) + "&6th=" + encodeURIComponent(selectedOption6) + "&7th=" + encodeURIComponent(selectedOption7) + "&8th=" + encodeURIComponent(selectedOption8) + "&9th=" + encodeURIComponent(selectedOption9) + "&10th=" + encodeURIComponent(selectedOption10);
section3.style.display="none";
section4.style.display="block";
var u = "www.yoururl.com";
var input = document.getElementById("1nameInput").value;
var inputt = document.getElementById("copytxt");
var inputname = "&name=";
var share = "&share=share";
var text = u + url1 + share + inputname + input;
inputt.value = text;
var $whatsApp = $('.whatsapp a');
decorateWhatsAppLink(text, input);
function decorateWhatsAppLink(text, input) {
// Getting user input
var message = "text";
// Opening URL
var url = 'whatsapp://send?text=';
//define the message text
var textttt = 'dare take this Challenge Now ';
//encode the text
//find the link
var $whatsApp = $('.whatsapp a');
//set the href attribute on the link
$whatsApp.attr('href', url + input + textttt + text);
}
url come from text variable
please tell me how to do
use encodeURIComponent on the whole URI not only the parameter values
so that & gets encoded as well ...
foo = "www.yoururl.com?1st=1&2nd=2&3rd=2&4th=1&5th=2&6th=2&7th=2&8th=2&9th=2&10th=2&share=share&name=s"
foo_final = encodeURIComponent(foo);
I have this function works well when i click the first time but when i click the second time receive a error in this part
eval("var " + data + "=sinvnword;");
Code:
$('a.play-video').click(function(){
var currentLocation = window.location;
var fullurl = window.location.href;
url = fullurl.split("sendx")[1];
var sinvnword = $('.question-label.active').last().text();
console.log(sinvnword);
var data =url ;
eval("var " + data + "=sinvnword;");
console.log(AXY + "GETIT");
console.log(AXY+"mor");
console.log(AXY + "muerte");
});
Rather than using eval to create dynamic variable names, simply use dynamic property names:
var data = {};
$('a.play-video').click(function(){
var currentLocation = window.location;
var fullurl = window.location.href;
var key = fullurl.split("sendx")[1];
var sinvnword = $('.question-label.active').last().text();
console.log(sinvnword);
data[key] = sinvnword;
console.log(AXY + "GETIT");
console.log(AXY+"mor");
console.log(AXY + "muerte");
});
I have an array of images that populate the page and what I am having trouble with is coming up with a way to create an ONCLICK popup image window from the thumbnails (but the popup window needs to be a bigger size image):
here is the js code:
var str = "<table>";
var imgFolder = "images/";
var cover = new Array();
cover[0] = "kitchenHouseSale.jpg";
cover[1] = "eatLive.jpg";
cover[2] = "loveAnthonySale.jpg";
var coverone = new Array();
coverone[0] = "casualVacancy.jpg";
coverone[1] = "quiet.jpg";
coverone[2] = "whirlAway.jpg";
var covertwo = new Array();
covertwo[0] = "everyLastSale.jpg";
covertwo[1] = "neilYoung.jpg";
covertwo[2] = "soupSisters.jpg";
var title = new Array();
title[0] = "The Kitchen House";
title[1] = "Eat to Live";
title[2] = "Love Anthony";
for (var i = 0; i < cover.length; i++)
{
str += "<tr><td colspan='2'><h2>" + category[i] + "</h2></td></tr>";
str += "<tr><td class='basket'><img src='" + imgFolder + cover[i] + "' width='108' height='159'>
}
str += "</table>";
var elem = document.getElementById("table");
elem.innerHTML = str;
Any help is appreciated. Thanks!
Do i get you right? You want the user to click on an image and a bigger version of the same image is supposed to appear in a popup-window?
Have a look at window.open() then: http://w3schools.com/jsref/met_win_open.asp
You must specify the absolute path of the image - file as the url for the popup, like http://your.domain.com/images/kitchenHouseSale.jpg.
you can then add an onclick-handler to the img-tag, something like this:
<img src='" + imgFolder + cover[i] + "' width='108' height='159' onclick="window.open('http://your.domain.com + this.src)" />
I am trying to retrieve data from a RSS feed (succeeding with this part) and then using the description, title and caption to be used to get Geo information (latitude, longitude, woeId) using YQL Placemaker open datatable.
This is all then needed to be output as JSON.
The permalink to test it in the YQL console is here.
Any ideas whats wrong with my xml code or what should I try instead?
<meta>
<author>Yahoo! Inc.</author>
<documentationURL>http://i-magine.mobi/</documentationURL>
<sampleQuery>select * from {table} where section="topstories" and description matches ".*jpg.*"</sampleQuery>
<description>Searches Yahoo.news RSS</description>
</meta>
<bindings>
<select itemPath="" produces="XML">
<urls>
<url>http://rss.news.yahoo.com/rss/topstories/{section}
</url>
</urls>
<inputs>
<key id='section' type="xs:string" paramType="path" required="true" />
</inputs>
<execute><![CDATA[
default xml namespace = "http://where.yahooapis.com/v1/schema.rng";
// http://www.json.org/json2.js
y.include('http://www.i-magine.mobi/json2.js');
rssStorySection = [];
rssStoryNumber = [];
rssStoryTitle = [];
rssStorySummary = [];
rssImageCaption = [];
rssStoryUrl = [];
rssImageUrl = [];
rssGeoText = [];
// var content = 'They followed him to deepest Africa after Brussels and Tokyo and found him there in Timbuktu';
var rssQuery = 'select * from rss where url = ' + "'" + 'http://rss.news.yahoo.com/rss/' + section + "'" + ' and description matches ".*jpg.*" limit 30';
res1 = y.query(rssQuery);
data1 = res1.results;
// var geoQuery = 'SELECT * FROM geo.placemaker WHERE documentContent =' + '"' + content + '"' + 'AND documentType=' + '"' + 'text/plain' + '"';
// res2 = y.query(geoQuery);
// data2 = res2.results;
for (var c=0;c<data1.item.length;c++)
{
var story = data1.item[c];
var storyTitleText0 = story.title + "";
var storyUrl = story.link + "";
var description = story.description;
var storyTitleText = storyTitleText0.replace(/\n/ig, "") + "";
var imageUrl = description.match(/http:\/\/d.*?jpg/i) + "";
var imageCaptionText0 = description.match(/alt="([^ ]).*border/) + "";
var imageCaptionText1 = imageCaptionText0.replace(/alt="/ig, "") + "";
var imageCaptionText = imageCaptionText1.replace(/" border.*/ig, "") + "";
var storySummaryText = description.replace(/<[^>]*>([\s]?)*<[^>]*>/g, "") + "";
var storySection0 = description.match(/http[^ ].*\*/i) + "";
var storySection1 = storySection0.replace(/\/\*/ig, "") + "";
var storySection = storySection1.replace(/http:\/\/us.rd.yahoo.com\/dailynews\/rss\//ig, "") + "";
var geoString = (imageCaptionText + " " + storyTitleText + " " + storySummaryText);
rssStorySection.push(storySection);
rssStoryTitle.push(storyTitleText);
rssStorySummary.push(storySummaryText);
rssImageCaption.push(imageCaptionText);
rssStoryUrl.push(storyUrl);
rssImageUrl.push(imageUrl);
rssGeoText.push(geoString);
rssStoryNumber.push(c);
var content = geoString;
var geoQuery = 'SELECT * FROM geo.placemaker WHERE documentContent =' + '"' + content + '"' + 'AND documentType=' + '"' + 'text/plain' + '"';
var res2 = y.query(geoQuery);
var data2 = res2.results;
}
var d = data1;
var e = data2;
response.object = <stories>
<c>{section}</c>
<d>{d}</d>
<e>{e}</e>
</stories>;
]]></execute>
</select>
</bindings>
</table>
A tidied up (and "working" in the sense that it brings back RSS+Placemaker results) version of your table looks like:
<?xml version="1.0" encoding="UTF-8" ?>
<table xmlns="http://query.yahooapis.com/v1/schema/table.xsd">
<meta>
<author>Peter Cowburn</author>
<documentationURL>http://stackoverflow.com/questions/6168564/creating-a-yql-opentable-to-combine-rss-data-with-placemaker-map-info</documentationURL>
<sampleQuery>select * from {table} where section='topstories'</sampleQuery>
<description>Searches Yahoo! News RSS and injects Placemaker Places</description>
</meta>
<bindings>
<select itemPath="stories.story" produces="XML">
<urls>
<url>
http://rss.news.yahoo.com/rss/{section}
</url>
</urls>
<inputs>
<key id="section" type="xs:string" paramType="path" required="true" />
</inputs>
<execute><![CDATA[
// Fetch top 30 feed items with jpg images
var feed = y.query(
'select * from rss where url=#url and description matches ".*jpg.*" limit 30',
{url: request.url}
).results;
// Build geo queries
var placeQuery = 'select * from geo.placemaker where documentContent=#text and documentType="text/plain"';
var placeQueries = [];
var title, description, caption, summary, content;
for each (result in feed.item) {
title = result.title.text().toString();
description = y.tidy(result.description.toString()).body.p;
caption = description.a.img.#alt.toString();
summary = description..*.text().toString();
content = caption + " " + title + " " + summary;
placeQueries.push({
query: y.query(placeQuery, {text: content}),
item: result,
results: null
});
}
// Execute all queries
var where = new Namespace('http://wherein.yahooapis.com/v1/schema');
var matches, match, places = [];
for (var q in placeQueries) {
matches = placeQueries[q].query.results.matches.match;
placeQueries[q].results = matches..where::place;
}
// Build response object
var stories = <stories/>;
for each (q in placeQueries) {
stories.node += <story>
{q.item}
{q.results}
</story>;
}
response.object = stories;
]]></execute>
</select>
</bindings>
</table>
You can use it by pointing to the table online (it may not be around forever!) in a query like:
use 'https://raw.github.com/salathe/yql-tables/so-6168564/yahoo/newswithplaces.xml'
as rssplaces;
select * from rssplaces where section='topstories';
(Try this in the YQL console)
The table uses some of the features available in <execute> blocks like E4X, query parameters and parallel queries which all make life easier but may be slightly foreign at first glance.
P.S. The above is offered as-is, I'm not going to be bending over backwards to field "support" questions on this. It is primarily intended as something to get you moving, an introduction to an approach which might work for you.