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.
Related
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()
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 want to create a script where I can upload files via event listener drop.
Everytime a file is dropped, a new table row has to be created with a save/edit button. These buttons need event listeners for click, but the problem is that the event listener works only on the last button added to the table.
I have made a simplified example of my problem. The function clickEventSaveButton() contains an .addEventlistener, with an anonymous function. For now it just executes a console log, but only for the button in the last table row. Everytime a new button is created, the old one stops working.
JS:
'use strict';
const dragArea = document.getElementById('dragArea');
const fileTable = document.getElementById('fileTable');
const fileTableBody = fileTable.querySelector('tbody');
let id = 0;
dragArea.addEventListener('dragover', (e) => {
e.preventDefault();
e.stopPropagation();
});
dragArea.addEventListener('drop', (e) => {
e.preventDefault();
e.stopPropagation();
// Add table row
fileTableBody.innerHTML += createFileTableRow(id, 'placeholder');
clickEventSaveButton(id);
id++;
});
function clickEventSaveButton(id) {
let saveButton = document.querySelector('.file-save a[data-id="'+id+'"]');
console.log(saveButton);
console.log(id);
saveButton.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
console.log('Save Button (ID:'+id+') pressed!');
});
}
function createFileTableRow(id, name) {
return `
<tr data-id="${id}">
<td class="file-name">${name}</td>
<td class="file-save">
<a data-id="${id}" class="button is-info is-small">Save</a>
</td>
</tr>
`;
};
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Security-Policy" content="script-src 'self';">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Test</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma#0.9.1/css/bulma.min.css">
<script defer src="test.js"></script>
</head>
<body>
<div class="columns"><div class="column is-half is-offset-one-quarter">
<h1>Work in progress</h1>
<div id="dragArea" class="box has-background-info-light has-text-centered py-6">
Drag .xlsx files here!
</div>
<hr>
<h3 id="fileTableTitle">No files loaded...</h3>
<table id="fileTable" class="table table is-fullwidth is-hoverable">
<thead><tr><th>File</th><th>Save File</th></tr></thead>
<tbody></tbody>
</table>
<hr>
</div></div>
</body>
</html>
So, thanks to Patrick Evans I was able to solve the issue that bugged me for some hours.
Instead of innerHTML I have to use insertAdjacentHTML.
Solution:
fileTableBody.insertAdjacentHTML('beforeend', createFileTableRow(id, 'placeholder'));
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 have a hta file which connects to a database via ADO and then prints to a table. However my code triggers a syntax error at the getstring line and a object does support property or method 'write' error at the document.write section of the code for the table. I am struggling to figure out how to use this getstring method as from my understanding it should be the most efficient way to print out the table.
<!DOCTYPE html>
<html>
<title>ARMS Hamburger Site</title>
<meta charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="ie=9">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<body>
<!-- Footer -->
<footer class="w3-center w3-light-grey w3-padding-32">
<button">Try it</button>
<script language="javascript">
var today = new Date();
var t0 = today.getSeconds();
var connection = new ActiveXObject("ADODB.Connection") ;
var table = document.getElementById("myTable");
var connectionstring="Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=\\\\drivepath\\blah\\filedatabase.accdb;Jet OLEDB:Engine
Type=5;Persist Security Info=False;Mode=Share Exclusive;"
connection.Open(connectionstring);
var rs = new ActiveXObject("ADODB.Recordset");
rs.Open("SELECT * FROM table", connection);
rs.MoveFirst
var str=rs.GetString(,,"</td><td>","</td></tr><tr><td>"," ");
rs.close;
connection.close;
var today2 = new Date();
var t1 = today2.getSeconds();
alert(t1-t0);
</script>
<center>
<table border="1" width="100%">
<tr>
<td><script language="javascript">document.Write(str)</script></td>
</tr>
</table>
</center>
<br>
</footer>
</body>
</html>