I am a newbie and rather a passionate starting to learn programming, than experienced guy.
I have done my research, yet unsuccessful, on how to get data from a Google Sheet and insert cell values into pre-made HTML template.
Task at hand is to generate employees email signatures prepared in HTML. Doing it manually was too time consuming and prone to mistakes.
Any change or update is really painful with this method.
I have found this tutorial and implemented it successfully
https://www.bpwebs.com/pull-data-from-google-sheets-to-html-table
After that I tried to replicate what was working in new project, but no results.
Ideally, expected result would be to run the app and be provided with as many ready HTML files as there are rows in the source Sheet file. There is also one condition, where one of the fields is to be displayed only for some employees (if blank, then insert nothing).
Please note I am very new to javascript, but eager to learn.
EDIT:
I have been asked to share what I have prepared by now. Cannot paste it in comments due to characters limit.
This is the Apps Script that shows simplified version of HTML that I am trying to manipulate. I was able to prepare a JS that changes name and surname as well as controls a portion of scr of img tag.
https://script.google.com/macros/s/AKfycbx6fapewLMLxgzrRKAY2bybR6HUngoA0sd-CaJHvXxF7TsbByqRWV_4cNpwzPAJJTJvpw/exec
(it should require Google account sing in. Unfortunately, option to share publicly disappeared)
I am also sharing a HTML with script put inside head section (in the Apps Script I have separate 'javascript' file that I am calling in HTML template file)
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght#300;600;800;900&display=swap" rel="stylesheet">
<script>
window.onload = function() {
//I need the var name to be pulling data from the Google Sheets
var name = 'blank-profile-picture-973460_1280';
var imgsrc = name;
document.getElementById('imgSource').src = 'https://cdn.pixabay.com/photo/2015/10/05/22/37/' + imgsrc + '.png';
var emName = 'Joe';
var emSurname = 'Doe';
document.getElementById('Name').innerHTML = emName
document.getElementById('Surname').innerHTML = emSurname
};
</script>
</head>
<body>
<table cellspacing="0" cellpadding="0" border="0" style="vertical-align:-webkit-baseline-middle;font-family:'Poppins', sans-serif;">
<tbody>
<td>
<td valign="middle" style="padding-left: 0px; padding-top: 0px; padding-bottom: 0px; padding-right: 20px;">
<span style="margin:0px;font-family:'Poppins', sans-serif;font-size:20px;font-weight:800; padding-top:5px;color:black" id="Name" ></span> <span style="margin:0px;font-family:'Poppins', sans-serif;font-size:20px;font-weight:800; padding-top:5px;color:#3d85c6" id="Surname"></span><br><img width="158" height="158" min-height="158" min-width="158" max-height="158" max-width="158" src="" id="imgSource">
</td>
</td>
</tbody>
</body>
</html>
In the article linked above, they are pulling whole table using array. Now I need to either map a whole columns (Name, Surname, img src) or specific cells to pull these values.
Best Regards,
Mac
Here is an example of how to create a table using both templated HTML and google.script.run
I create a simple spreadsheet as shown.
Next in Code.gs I create my scripts
function showTest() {
var html = HtmlService.createTemplateFromFile("HTML_Test");
SpreadsheetApp.getUi().showModalDialog(html.evaluate(),"Test");
}
function getData() {
try {
let spread = SpreadsheetApp.getActiveSpreadsheet();
let sheet = spread.getSheetByName("Sheet2");
let values = sheet.getDataRange().getDisplayValues();
values.shift(); // remove header
return values;
}
catch(err) {
Logger.log(err);
}
}
For templated HTML I create my page HTML_Test.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<style>
table, th, td {
border:1px solid black;
}
</style>
</head>
<body>
<? var data = getData(); ?>
<table>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<? for (var i = 0; i < data.length; i++) { ?>
<tr>
<td><?= data[i][0] ?></td>
<td><?= data[i][1] ?></td>
</tr>
<? } ?>
</table>
</body>
</html>
Or using an Immediately Invoked Function HTML_Test
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<style>
table, th, td {
border:1px solid black;
}
</style>
</head>
<body>
<table id="table">
</table>
<script>
( function () {
try {
google.script.run.withSuccessHandler(
function (data) {
let table = document.getElementById("table");
for( let i=0; i<data.length; i++ ) {
let row = document.createElement("TR");
let cell = document.createElement("TD");
let text = document.createTextNode(data[i][0]);
cell.appendChild(text);
row.appendChild(cell);
cell = document.createElement("TD");
text = document.createTextNode(data[i][1]);
cell.appendChild(text);
row.appendChild(cell);
table.appendChild(row);
}
}
).getData();
}
catch(err) {
alert(err);
}
}
)();
</script>
</body>
</html>
And the results are
Reference
Templated HTML
google.script.run()
Related
I have a website table that shows a variety of data, which currently changes which data are viewed based on a variable string passed in the URL. This example looks as follows:
www.acoolwebsite.com/?variable=var1
I've provided a synthesized view of the table's current header structure, which is as follows:
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<table>
<tr>
<th>Static1</th>
<th>Static2</th>
<th>Static3</th>
<th>Variable1</th>
<th>Variable2</th>
<th>Variable3</th>
</tr>
</table>
</body>
</html>
I am looking to change the headers Variable1, Variable2, & Variable3 to another set of headers, say Change1, Change2, & Change3 if the passed variable in the URL www.acoolwebsite.com/?variable=var1 matches a certain string.
Using JavaScript, I've been able to partition the variable passed in the URL, but am uncertain how to isolate and alter header names. What additional steps can I take to produce this outcome?
You should assign an ID for your table headers and use innerHTML. See sample snippet below:
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<table>
<tr>
<th>Static1</th>
<th>Static2</th>
<th>Static3</th>
<th id="v1">Variable1</th>
<th id="v2">Variable2</th>
<th id="v3">Variable3</th>
</tr>
</table>
<input type="button" value="Click" onclick="changeHeaders()" />
<script>
function changeHeaders() {
// You variables
let v1 = 'change1';
let v2 = 'change2';
let v3 = 'change3';
document.getElementById("v1").innerHTML = v1;
document.getElementById("v2").innerHTML = v2;
document.getElementById("v3").innerHTML = v2;
}
</script>
</body>
</html>
https://levelup.gitconnected.com/building-a-simple-website-that-outputs-results-from-a-csv-using-users-input-bfcb782ced45
Hi, I am new to JavaScript. I came across this above tutorial and am trying to get it working so that i can then modify it for a little project i am working on. I hope to learn from it as I progress my project. I cant learn at the moment as I dont know whether its right or wrong.
I have created the html and JS file and have tested that they are linked. (I wrote an alert in the JS file that got triggered in the html file. I also added a quick script that gave a text alert when the button was pushed in html file).
I believe I have the same CSV file that the author was using but I cant be 100%. I can only assume I have introduced some error in the JS file and therefore its not reading the CSV file correctly. I have been at this for days and come up with nothing. Any help greatly appreciated.
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8">
<meta name=”viewport” content=”width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
<div class=”container”>
<div class=”row”>
<div class=”col-md-12">
<h1 class=>Find Movies!</h1>
<h2 class=>Enter the name of an actor/actress to see his/her best movies!</h2>
<form id=”form”>
<input class=”form-control” id=”user-input” placeholder=”Enter actor/actress…”>
<button id=”button” class=”btn btn-secondary”>Find Movies!</button>
</form>
<table class="table" cellpadding="10">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Movie</th>
<th scope="col">Rating</th>
<th scope="col">Year</th>
<th scope="col">Description</th>
</tr>
</thead>
<tbody>
</div>
</div>
</div>
<script src="app.js" charset="utf-8"> </script>
</body>
</html>
JavaScript (app.js)
d3.csv("movies.csv").then(function (data) {
var movies = data;
var button = d3.select("#button");
var form = d3.select("#form");
button.on("click", runEnter);
form.on("submit", runEnter);
function runEnter() {
d3.select("tbody").html("")
d3.event.preventDefault();
var inputValue = d3.select("#user-input").property("value");
var filteredMovies =
movies.filter(movies => movies.actors.includes(inputValue));
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js"></script>
var output = _.sortBy(filteredMovies, 'avg_vote').reverse()
for (var i = 0; i < filteredMovies.length; i++) {
d3.select("tbody").insert(“tr").html(
"<td>" + [i+1] + "</td>" +
"<td>" + (output[i]['original_title'])+”</a>”+“</td>” +
"<td>" + (output[i]['avg_vote'])+"</td>" +
"<td>" + (output[i]['year'])+"</td>" +
"<td>" + (output[i]['description'])+"</td" ) }
};
});
Extract from movies.csv
I'm working in VSCODE. I have an html page and I want to include an external javascript file in it.
this is the html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Javascript Exercise</title>
<link rel="stylesheet" href="./assets/css/styles.css">
</head>
<body onload="addTable()">
<div class="title">Reports</div>
<!-- singolo run test -->
<div class="block">
<h1> Ultimo test eseguito </h1>
<div id="myDynamicTableTitles" class="table"></div>
<div id="myDynamicTable" class="table"></div>
</div>
<!-- JAVASCRIPT -->
<script src="./index.js"></script>
</body>
</html>
I know for sure that the js I wrote works, because if I put the js directly inside the <script></script> the page works.
Any idea on why, if I put it into an external file, it doesn't load? I'm also sure that the path "./index.js" it's correct.
I've noticed that if I click directly on the file html it works (like from the computer explorer). But if I load the project trough VSCode, it doesn't.
when I execute npm start it compile and gives me an http://localhost:xxxx
To make an example...
Maybe the script have an error?
function addTable(table) {
//Maybe you miss something? Here's an example
// get the reference for the body
var body = document.getElementsByTagName("body")[0];
// creates a <table> element and a <tbody> element
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
// creating all cells
for (var i = 0; i < 2; i++) {
// creates a table row
var row = document.createElement("tr");
for (var j = 0; j < 2; j++) {
// Create a <td> element and a text node, make the text
// node the contents of the <td>, and put the <td> at
// the end of the table row
var cell = document.createElement("td");
var cellText = document.createTextNode("cell in row "+i+", column "+j);
cell.appendChild(cellText);
row.appendChild(cell);
}
// add the row to the end of the table body
tblBody.appendChild(row);
}
// put the <tbody> in the <table>
tbl.appendChild(tblBody);
// appends <table> into <body>
body.appendChild(tbl);
// sets the border attribute of tbl to 2;
tbl.setAttribute("border", "2");
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Javascript Exercise</title>
<link rel="stylesheet" href="./assets/css/styles.css">
</head>
<body onload="addTable()"></body>
<div class="title">Reports</div>
<!-- singolo run test -->
<div class="block">
<h1> Ultimo test eseguito </h1>
<div id="myDynamicTableTitles" class="table"></div>
<div id="myDynamicTable" class="table"></div>
</div>
<!-- JAVASCRIPT -->
<script src="./index.js"></script>
<!-- add this -->
</body>
</html>
You can find more explanations of this JScode in this great page
Divertiti
I've noticed that if I click directly on the file html it works (like from the computer explorer). But if I load the project trough VSCode, it doesn't.
It sounds like you are using the Live HTML Previewer extension which says:
Note: Javascript is not supported in preview
Use a browser to test your browser-dependant JS.
I am trying to duplicate Expanding Text Areas Made Elegant
Basically it explains how we can achieve something like fb comment box, where its size increases as text files the textarea.
I have this in my index.html:
<html>
<head>
<link rel="stylesheet" type="text/css" href="test.css">
<script src="test.js"></script>
</head>
<body>
<figure>
<div class="expandingArea">
<pre><span></span><br></pre>
<textarea></textarea>
</div>
</figure>
</body>
</html>
And my test.js looks like:
This doesn't really works.
However if I move everything inside the js file to a script tag inside body then it works fine. So my index file would look like:
<html>
<head>
<link rel="stylesheet" type="text/css" href="test.css">
</head>
<body>
<figure>
<div class="expandingArea">
<pre><span></span><br></pre>
<textarea></textarea>
</div>
</figure>
<script>
function makeExpandingArea(container) {
var area = container.querySelector('textarea');
var span = container.querySelector('span');
if (area.addEventListener) {
area.addEventListener('input', function() {
span.textContent = area.value;
}, false);
span.textContent = area.value;
} else if (area.attachEvent) {
// IE8 compatibility
area.attachEvent('onpropertychange', function() {
span.innerText = area.value;
});
span.innerText = area.value;
}
// Enable extra CSS
container.className += ' active';
}var areas = document.querySelectorAll('.expandingArea');
var l = areas.length;while (l--) {
makeExpandingArea(areas[l]);
}
</script>
</body>
</html>
You're not actually using onload
Your formatting is so messed up it's hard to tell, but your init code is in a while loop at the bottom after your onload function.
When you include it in the <head> it runs before any elements exist. That's why the position of it matters.
In your browser(I recommend Chrome for testing) open up the developer tools(via right click and selecting inspect element) and make sure your test.js file's path is correct. Do this by selecting the 'Sources' tab on the top of the developer tools window and then selecting the test.js file on the list of sources.
I also consider it best practice to load your js files at the bottom of your web documents(before the last body tag) to guarantee they load AFTER your dom elements load.
try this in your code:
I have used inside a table andapply a css class "form-control". The properties of this text areas are in side tag in side
html code:
<html>
<body>
<table>
<tr>
<td>Description:</td>
<td><textarea name="DESCRIPTION" id="DESCRIPTION" class="form-control"></textarea></td>
<td></td>
</tr>
</table>
//css-code required inside html:
<style>
textarea.form-control {
height: auto;
resize: none;
width: 300px;
}
</style>
</body>
</html>
I have a javascript file which contains some data array and a function. I am using this function to display a table on the html page when it loads and on the click of a button. The error I am getting is:
GET http://localhost:3000/views/table.js contracts.html:84
Uncaught ReferenceError: addTable is not defined contracts.html:84 onclick
My contracts.html file looks like this:
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<link rel="stylesheet" href="/css/portalstyle.css">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
</head>
<body id="contracts">
<div id="wrapper">
<!-- Some Header code here -->
<div id="mytable"></div>
<div id="footer">
<table id="footer" style="width: 100%">
<tr>
<td valign="bottom">Company Name
<br />Tel Num
<br />Location, Postcode</td>
<td>
<button onclick="addTable(ORDER.orders)">Click me</button>
</td>
<td align="right" valign="bottom">
Home About Help Contact
</td>
</tr>
</table>
</div>
</div>
<hr />
<script src="http://getbootstrap.com/dist/js/bootstrap.min.js"></script>
<script src="../views/table.js"></script>
</body>
</html>
My javascript function file is called table.js and contains:
var ORDER = {
orders: []
};
function Order(ref, grower, item) {
this.order_reference = ("o" + ref);
this.grower_reference = grower;
this.item_ordered = item;
}
var order1 = new Order(1, "grower2", "item");
ORDER.orders.push(order1);
function addTable(orders) {
var table = document.createElement("TABLE");
table.setAttribute("id", "myTable");
document.body.appendChild(table);
for (var i = 0; i < orders.length; i++) {
var order = orders[i];
var row = document.createElement("TR");
var refCell = document.createElement("TD");
var growerCell = document.createElement("TD");
var itemCell = document.createElement("TD");
row.appendChild(refCell);
row.appendChild(growerCell);
row.appendChild(itemCell);
var ref = document.createTextNode(order.order_reference);
var grower = document.createTextNode(order.grower_reference);
var item = document.createTextNode(order.item_ordered);
refCell.appendChild(ref);
growerCell.appendChild(grower);
itemCell.appendChild(item);
table.appendChild(row);
document.body.appendChild(document.createElement('hr'));
}
}
window.addEventListener('load', function() {
addTable(ORDER.orders)
});
Where do I need to define addTable? How should I do this?
Also, the error with the GET. This is the line where I include the script. How can I stop this error occurring?
Thank you for the suggestions. They helped me to look at the correct piece of code to find the error so I have no fixed it.
It was an error with my folders and the path I was specifying. I originally had my .js file in my 'views' folder and was using ../views/table.js. This threw the not defined error so I created a new folder called 'js' and copied the file into here and specified it using /js/table.js and now it works.
From what I understand ../ looked in the parent directory of the folder I was in, whereas I needed to be 2 folders up, so starting with just a slash started the search from the root directory, found a folder called js and then found the addTable function as expected.