JS ReferenceError: getActivityTables is not defined at onload [duplicate] - javascript

This question already has answers here:
How to run a function when the page is loaded?
(11 answers)
Closed 2 months ago.
Why is getActivityTables() not defined? The script is properly linked, and the function name is the same in the html as well as js file.
What am I doing wrong?
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Fitnessapp</title>
<script src="scripts.js"></script>
</head>
<body onload="getActivityTables()">
<div id="" class="container">
<div class="activityDiv">
<h1>Running Activities</h1>
<table id="runningActivity-table" class="table">
</table>
</div>
</div>
</body>
</html>
JS (scripts.js):
function getActivityTables() {
console.log("test");
// Get runningActivity-table
let xhttp = new XMLHttpRequest();
xhttp.onload = function () {
let response;
let responseString = xhttp.responseText;
response = JSON.parse(responseString);
console.log(response);
let table = document.getElementById("runningActivity-table");
let row, cell;
let header = table.createTHead();
row = header.insertRow(0);
cell = row.insertCell();
cell.innerHTML = "ID";
cell = row.insertCell();
cell.innerHTML = "Date";
cell = row.insertCell();
cell.innerHTML = "Duration";
cell = row.insertCell();
cell.innerHTML = "Distance";
cell = row.insertCell();
cell.innerHTML = "Description";
for (let i = 0; i < response.length; i++) {
row = table.insertRow();
cell = row.insertCell();
cell.textContent = response[i].id;
cell = row.insertCell();
cell.textContent = response[i].dateOfCreation;
cell = row.insertCell();
cell.textContent = response[i].durationInMinutes;
cell = row.insertCell();
cell.textContent = response[i].distanceInKm;
cell = row.insertCell();
cell.textContent = response[i].description;
}
}
xhttp.open("GET", "/getRunningActivities");
xhttp.send();
}
I cannot find the problem. I have the exact same code for another page and thats working properly.

I copied your entire code exactly in my vs code, and launched it, and everything is working.
The getActivityTables function worked fine.
But you can try to use the addEventListener() inside the javascript itself, it's better than the regular html events attributes.
But your code doesn't have any problems, I tried it myself.
You can capture the console and the network tab in your browser then we can figure out what's happened.

try to remove <script src="scripts.js"></script> from the head tag And put it at the end of the Body tag
like this :
<body onload="getActivityTables()">
<div id="" class="container">
<div class="activityDiv">
<h1>Running Activities</h1>
<table id="runningActivity-table" class="table">
</table>
</div>
</div>
<script src="scripts.js"></script>
</body>
if problem still
in scripts.js file add :
window.addEventListener('load',getActivityTables())

Related

is there a way to assign id or classname to an element through document.createElement?

Im still relatively new to JS. I know i probably shouldnt write my code the way i have done here in the real world, but im only doing this to test my knowledge on for loops and pulling JSON data.
My question is, with the way i have structured my code, is it possible for me to add classnames/Id's to the elements i have made using doc.createElement? for example if i wanted to add custom icons or buttons to each element? I cant seem to think of a way to add them other than having to write out all the HTML and do it that way. Here's my code :
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./styles.css">
<title>Document</title>
</head>
<body>
<section>
</section>
<script src="./app.js"></script>
</body>
</html>
JS
const allCustomers = document.querySelector("section");
let custName = "";
let username = "";
let email = "";
let id = "";
const requestURL = "https://jsonplaceholder.typicode.com/users";
fetch(requestURL)
.then((response) => response.text())
.then((text) => DisplayUserInfo(text));
function DisplayUserInfo(userData) {
const userArray = JSON.parse(userData);
for (i = 0; i < userArray.length; i++) {
let listContainer = document.createElement("div");
let myList = document.createElement("p");
let myListItems = document.createElement("span");
myList.textContent = `Customer : ${userArray[i].name}`;
myListItems.innerHTML =`<br>ID: ${userArray[i].id} <br>Email: ${userArray[i].email} <br>Username: ${userArray[i].username}`;
myListItems.appendChild(myList);
listContainer.appendChild(myListItems);
allCustomers.appendChild(listContainer);
}
}
DisplayUserInfo();
Any pointers would be greatly appreciated as well as any constructive feedback. Thanks
Yes, for sure you can add any attribute for a created element. element.classList.add('class-name-here') for adding class, element.id = 'id-name-here' for adding id.
const allCustomers = document.querySelector("section");
let custName = "";
let username = "";
let email = "";
let id = "";
const requestURL = "https://jsonplaceholder.typicode.com/users";
fetch(requestURL)
.then((response) => response.text())
.then((text) => DisplayUserInfo(text));
function DisplayUserInfo(userData) {
const userArray = JSON.parse(userData);
for (i = 0; i < userArray.length; i++) {
let listContainer = document.createElement("div");
let myList = document.createElement("p");
myList.classList.add('active');
myList.id = 'paragraph'
let myListItems = document.createElement("span");
myList.textContent = `Customer : ${userArray[i].name}`;
myListItems.innerHTML =`<br>ID: ${userArray[i].id} <br>Email: ${userArray[i].email} <br>Username: ${userArray[i].username}`;
myListItems.appendChild(myList);
listContainer.appendChild(myListItems);
allCustomers.appendChild(listContainer);
}
}
DisplayUserInfo();
.active {
color: red;
}
#paragraph {
font-size: 24px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./styles.css">
<title>Document</title>
</head>
<body>
<section>
</section>
<script src="./app.js"></script>
</body>
</html>
is it possible for me to add classnames/Id's to the elements i have
made using doc.createElement
Yes possible with classList for adding class and setAttribute to add id
let listContainer = document.createElement("div");
// To add class
listContainer.className = 'your-class'; //if you have just one
listContainer.classList.add("my-class");//if you want to add multiple
// To add id
listContainer.setAttribute("id", "your_id");
When you use document.createElement it returns an Element. You can use Element attributes and methods to reach what you need. There are some docs for this class on MDN.
This means you can:
> myDiv = document.createElement("div")
<div></div>
> myDiv.id = "test"
'test'
> myDiv
<div id="test"></div>
For classes you can use the attributes className or classList.

Javascript cloneNode for adding new elements

what I'm trying to do is. when I click
function runIt(text) {
var counter = 1;
var comment = document.getElementById("name");
comment.innerText = text;
comment.cloneNode(true);
comment.id += counter;
}
document.addEventListener("click", function(e){
runIt("test")
}, true);
I want it to ADD a new element underneath that output "test".
it's keep getting replaced. :(
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>t</title>
</head>
<body>
<p id="name" class="someclass"></p>
</body>
</html>
cloneNode returns the new code, which you can then append to the DOM. Also counter should be defined outside the function and then incremented each time.
var counter = 1;
function runIt(text) {
var comment = document.getElementById("name");
newcomment = comment.cloneNode(true);
newcomment.innerText = text;
newcomment.id += counter;
counter++;
document.querySelector('body').append(newcomment)
}
document.addEventListener("click", function(e){
runIt("test")
}, true);
<p id="name" class="someclass">-</p>

I am not sure I can access the second html file using one js file, html element is showing as null when it is a button

I have 2 html files connected to one js file. When I try to access a html element in the second html file using js it doesn't work saying that is is null. I did
let elementname = document.getElementById("element") for a element in the second html page then
console.log(elementname) and it says it is null. When I do it for a element in the first html page it says HTMLButtonElement {}
Here is the html for the first Page
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Not Quuuuiiiizzzz</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>Not Quuuuiiiizzzz</h1>
<h2>Join a quiz</h2>
<!--Buttons -->
<div style="text-align: center;">
<button id="btnforquiz1" onclick="gotoquiz()"></button>
<button id="btnforquiz2" onclick="gotoquiz1()"></button>
<button id="btnforquiz3" onclick="gotoquiz2()"></button>
</div>
<h2 id="h2">Create a Quuuuiiiizzzz</h2>
<script src="script.js"></script>
</body>
</html>
For the second page
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Not Quuuuiiiizzzz</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body onload="quizLoad()">
<h1 id="question">Hello</h1>
<button id="answer1"></button>
<button id="answer2"></button>
<button id="answer3"></button>
<button id="answer4"></button>
<script src="script.js"></script>
</body>
</html>
And Finally for the js file :
//setting global variables
let btn1 = document.getElementById("btnforquiz1") //getting button with id of btnforquiz1 repeat below
correct = 0
let btn2 = document.getElementById("btnforquiz2")
let btn3 = document.getElementById("btnforquiz3")
let question = document.getElementById("question")
let answer1 = document.getElementById("answer1")
let answer2 = document.getElementById("answer2")
let answer3 = document.getElementById("answer3")
let answer4 = document.getElementById("answer4")
quizNameRel = -1;
cosnole.log(question)
console.log(answer1)
//Quiz Data
Quiz_1 = {
"What is the capital of buffalo":["Idk", "Yes", "No",0],
"What is the smell of poop": ["Stinky"]
};
Quiz_2 = [
"What is wrong with you"
];
Quiz_3 = [
"What is wrong with you #2"
]
let quiz = {
name: ["History Test", "Math Practice", "ELA Practice"],
mappingtoans: [0,1,2],
QA: [Quiz_1, Quiz_2, Quiz_3]
}
//quiz data
//when body loades run showQuizzs function
document.body.onload = showQuizzs()
function showQuizzs() {
//loops throo the vals seeting the text for the btns
for (let i = 0; i < quiz.name.length; i++) {
btn1.textContent = quiz.name[i-2]
btn2.textContent = quiz.name[i-1]
btn3.textContent = quiz.name[i]
}
}
//leads to the showQuizzs
function gotoquiz() {
location.href = "quiz.html"
quizNameRel = quiz.name[0]//I was trying to create a relation so we could knoe which quiz they wnt to do
startQuiz()
}
function gotoquiz1() {
location.href = "quiz.html"
quizNameRel = quiz.name[1]
startQuiz()
}
function gotoquiz2() {
location.href = "quiz.html";
quizNameRel = quiz.name[2];
startQuiz();
}
function answerselect(elements){
whichone = Number(elements.id.slice(-2,-1))
if(Quiz_1[whichone]==Quiz_1[-1]){
correct+=1;
NextQuestion();
}else{
wrong+=1;
}
}
//gets the keys and puts it into an array
function getkeys(dictionary){
tempdict = [];
for(i in dictionary){
tempdict.push(i);
}
return tempdict;
}
function setQuestion() {
let tempdict = getkeys(Quiz_1)
console.log(tempdict, getkeys(Quiz_1));
//question.innerHTML = tempdict;
}
// startQuiz
function startQuiz() {
switch (quizNameRel){
case quiz.name[0]:
//case here
setQuestion()
break
case quiz.name[1]:
//case here
break
case quiz.name[2]:
//case here
break
}
}
//TO DO:
// Set the question
// Set the answer
// Check if correct button
This is happening because at a time you have rendered only one html file. For example if you render index1.html(first file) then your js will look for rendered element from first file only but here index2.html(second file) is not rendered so your js script is unable to find elements of that file that's the reason it shows null.
If you try to render now index2.html rather than index1.html then you will find now elements from index2.html are detected by js script but elements from index1.html are null now.

Displaying content of xml data in html file is not working

I want to display the content of a XML file into a html file.
I have seen and tried the example shown in the following link
https://www.youtube.com/watch?v=VxKGVb0oOBw
I have created html file copying the exactly the code in that example. Here is the code of my first html file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=""UTF-8>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Test 1oading xml</title>
</head>
<body>
<div id='content'>
<table id="books" cellpadding="10px" style="text-align:left;">
<thead>
<tr><th>Author</th><th>Title</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<script>
let xmlContent = '';
let tableBooks = document.getElementById('books');
fetch('books.xml').then((response)=>{
response.text().then((xml)=>{
xmlContent = xml;
let parser = new DOMParser();
let xmlDOM = parser.parseFromString(xmlContent, 'appliction/xml');
let books = xmlDOM.querySelectorAll('book');
books.forEach(bookXmlNode => {
let row = document.createElement('tr');
//author
let td = document.createElement('td');
td.innerText = bookXmlNode.children[0].innerHTML;
row.appendChild(td);
//title
let td = document.createElement('td');
td.innerText = bookXmlNode.children[1].innerHTML;
row.appendChild(td);
tableBooks.children[1].appendChild(row);
});
});
});
</script>
</body>
</html>
copied the xml file content from here https://learn.microsoft.com/en-us/previous-versions/windows/desktop/ms762271(v%3Dvs.85) .. saved the file as books.xml in the same folder of the html file. Although Ideally I want to display data from external xml file so that the data can be updated dynamically.
When I open the html file it is not showing the xml data.
I have also tried with the code from this link.
https://www.encodedna.com/2014/07/extract-data-from-an-xml-file-using-javascript.htm
Thant is also not working.
How to display data of an (external) xml file into a html file
Screenshot of inspect page. The top one for the code of the you tube video.
The botom one is for the code from https://www.encodedna.com/2014/07/extract-data-from-an-xml-file-using-javascript.htm
Your code is basically correct but you have a few typos. Try the code below, which works for me. As other commenters have mentioned, you can't just open the file, you need a web server to serve it up. The video you link to does this using Live Server in Visual Studio Code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="" UTF-8>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Test 1oading xml</title>
</head>
<body>
<div id='content'>
<table id="books" cellpadding="10px" style="text-align:left;">
<thead>
<tr>
<th>Author</th>
<th>Title</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<script>
let xmlContent = '';
let tableBooks = document.getElementById('books');
fetch('books.xml').then((response) => {
response.text().then((xml) => {
xmlContent = xml;
let parser = new DOMParser();
let xmlDOM = parser.parseFromString(xmlContent, 'application/xml');
let books = xmlDOM.querySelectorAll('book');
books.forEach(bookXmlNode => {
let row = document.createElement('tr');
//author
let td = document.createElement('td');
td.innerText = bookXmlNode.children[0].innerHTML;
row.appendChild(td);
//title
let td2 = document.createElement('td');
td2.innerText = bookXmlNode.children[1].innerHTML;
row.appendChild(td2);
tableBooks.children[1].appendChild(row);
});
});
});
</script>
</body>
</html>
The typos are: id="books", 'application/xml' and you can't use td as a variable name twice.
By the way, when you have problems like this the first place to look is in the browser's console window. Hit F12 after the browser has launched and failed to show your data, and go to Console if it's not selected: it will show you any errors and where they are coming from. If you're using VS Code you can actually debug the script as well I think, meaning you can single-step through it seeing what's going on.

Creating unique Id buttons in a javascript loop

I need to create a table populated with buttons. Each button must have a unique id in order to edit values in it's row. I set an alert displaying button's id on click, but all created buttons seem to have the same ID. What's wrong with my code?
plz help, im really newbie in js. Any help will be highly appreciated.
this is my code:
<!doctype html>
<html>
<head>
<title>js table</title>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<table id="TableA" dir="ltr" width="500" border="1">
<tr>
<td>Old top row</td>
</tr>
</table>
</body>
<script type="text/javascript" >
for (var i = 0; i<6; i++) {
// Get a reference to the table
var tableRef = document.getElementById("TableA");
// Insert a row in the table at row index 0
var newRow = tableRef.insertRow(0);
// Insert a cell in the row at index 0
var boton = newRow.insertCell(0);
// Append a text node to the cell
var newButton = document.createElement("BUTTON");
newButton.id = i;
newButton.innerHTML = "Unique id button";
boton.appendChild(newButton);
// Insert a cell in the row at index 0
var newCell = newRow.insertCell(0);
// Append a text node to the cell
var newText = document.createElement("P");
newText.innerHTML = "item" +" "+ i;
newCell.appendChild(newText);
newButton.onclick = function(){
alert("Button Id: " + newButton.id);
}
}
</script>
Change your client handler to refer to the actual button that was clicked. Change from this:
newButton.onclick = function(){
alert("Button Id: " + newButton.id);
}
to this:
newButton.addEventListener("click", function(e) {
alert("Button Id: " + this.id);
});
The variable newButton is used over and over again in your for loop so by the time any of your onclick handlers actually run, all the buttons have been created and newButton will contain the last value it ever had.
Instead, you can use this to refer to the element that was clicked on so this.id will the id value of the button that was clicked.
Note: I also switch to using .addEventListener() which also passes an event data structure to the event handler (shown as the e argument in my code). This is a generally better way to register event listeners as it allows multiple listeners and gives you automatic access to other info about the event that occurred.

Categories