I am trying to calculate values using javascript then update the HTML with them. If I don't defer both scripts then I get the error
"Uncaught TypeError: Cannot set properties of null (setting 'innerHTML') at updateDetailsHTML (breakeven-calc.js:2) at (index):72"
If I defer both scripts I get the error
"(index):72 Uncaught ReferenceError: updateDetailsHTML is not defined at (index):72"
HTML Coded
<head>
<script defer src="../static//js/breakeven-calc.js"></script>
<script defer type="text/javascript"> /* Creates vars to pass to function */
let G22_Car = parseFloat("{{data.get('G22_Car')}}")
let G23_Car = parseFloat("{{data.get('G23_Car')}}")
let Q23_Car = parseFloat("{{data.get('Q23_Car')}}")
let Q24_Car = parseFloat("{{data.get('Q24_Car')}}")
let G22_Truck = parseFloat("{{data.get('G22_Car')}}")
let G23_Truck = parseFloat("{{data.get('G23_Car')}}")
let Q23_Truck = parseFloat("{{data.get('Q23_Truck')}}")
let Q24_Truck = parseFloat("{{data.get('Q24_Truck')}}")
let pre_icev_car = G22_Car + G23_Car
let pre_ev_car = Q23_Car + Q24_Car
let pre_icev_truck = G22_Truck + G23_Truck
let pre_ev_truck = Q23_Truck + Q24_Truck
console.log(pre_ev_car)
console.log(pre_icev_car)
console.log(pre_ev_truck)
console.log(pre_icev_truck)
/* Function in breakeven-calc*/
updateDetailsHTML(pre_icev_car, pre_ev_car, pre_icev_truck, pre_ev_truck)
</script>
</head>
<body>
<p id="car-details">
Pre-ownership CO2e emissions (reference values apply): <br>
EV: MTCO2e/Year <br>
ICEV: MTCO2e/Year
</p>
</body>
Javascript file "breakeven-calc"
function updateDetailsHTML(pre_icev_car, pre_ev_car, pre_icev_truck, pre_ev_truck){
document.getElementById("car-details").innerHTML = "worked"
}
copy paste as below
<!doctype html>
<html>
<head>
<script>
<!--
let G22_Car = parseFloat("{{data.get('G22_Car')}}")
let G23_Car = parseFloat("{{data.get('G23_Car')}}")
let Q23_Car = parseFloat("{{data.get('Q23_Car')}}")
let Q24_Car = parseFloat("{{data.get('Q24_Car')}}")
let G22_Truck = parseFloat("{{data.get('G22_Car')}}")
let G23_Truck = parseFloat("{{data.get('G23_Car')}}")
let Q23_Truck = parseFloat("
{{data.get('Q23_Truck')}}")
let Q24_Truck = parseFloat("
{{data.get('Q24_Truck')}}")
let pre_icev_car = G22_Car + G23_Car
let pre_ev_car = Q23_Car + Q24_Car
let pre_icev_truck = G22_Truck + G23_Truck
let pre_ev_truck = Q23_Truck + Q24_Truck
console.log(pre_ev_car)
console.log(pre_icev_car)
console.log(pre_ev_truck)
console.log(pre_icev_truck)
/* Function in breakeven-calc*/
function updateDetailsHTML(pre_icev_car, pre_ev_car,
pre_icev_truck, pre_ev_truck){
document.getElementById("car-details").innerHTML =
"worked"
updateDetailsHTML(pre_icev_car, pre_ev_car,
pre_icev_truck, pre_ev_truck)
}
-->
</script>
</head>
<body>
<div id='car-details'>
Pre-ownership CO2e emissions (reference values apply):
<br>
EV: MTCO2e/Year <br>
ICEV: MTCO2e/Year
</div>
</body>
</html>
Regarding the defer script , you wont need that , it only affect the code within the script if it only has src attribute on it .
and make sure you define the function above then call it in sequence
Have you ever tried moving your scripts inside your body tag?
<body>
<p id="car-details">
Pre-ownership CO2e emissions (reference values apply): <br>
EV: MTCO2e/Year <br>
ICEV: MTCO2e/Year
</p>
{{-- put all your scripts here--}}
</body>
Related
My message does not display after I run the code. Need some direction, I double checked my code. Might be a syntactical error somewhere
HTML-
<!doctype html>
<html>
<head>
<title>Message Generator</title>
<link rel="stylesheet" href="index.css">
<center><div class="wordart blues"><span class="text">Message Generator</span></div></center>
</head>
<body>
<div class="quoteDisplay"><center>Your random message will be displayed here</center></div>
<div id="quote">
<!--Quote will display here-->
</div>
<center><button onclick="messageGenerator()">Click Here</button></center>
<script src="index.js"></script>
</body>
</html>
Javascript-
const first = ["Mom", "Dad", "Uncle", "Dog", "Cat", "Brother", "Sister", "Aunt", "Random Stranger", "Respect", "Honor", "Dignity", "Brain", "Life"]
const second = ["Ocean", "Sea", "Volcano", "Tornado", "Ditch", "Cave", "Typhoon", "Asia", "India"]
const third=["Unknown","To explore","To prove a point","To live life with no constraints","Just cause"]
function randomGenerate(value) {
var item = value[Math.floor(Math.random() * value.length)];
return item;
}
const messageGenerator = () => {
let person = randomGenerate(first);
let place = randomGenerate(second);
let reason = randomGenerate(third);
let finalSentence = `Your ${person} jumped in the ${place}\nReason: ${reason}`;
document.getElementById("quoteDisplay").innerHTML=finalSentence;
}
document.getElementById("quoteDisplay") looks for an element with ID of "quoteDisplay". In this case, your targeted element is a class.
document.querySelector('.quoteDisplay').innerHTML = finalSentence
Although, I think you are trying to target #quote, which in this case, getElementById is the right method but the wrong id
document.getElementById("quote").innerHTML = finalSentence;
Looking at your HTML
<div class="quoteDisplay"><center>Your random message will be displayed here</center></div>
<div id="quote">
Looking at your javascript
document.getElementById("quoteDisplay").innerHTML=finalSentence;
It should be document.getElementById("quote").innerText = finalSentence;
I am trying to implement the following code in which i try to read a json file in javascript. I have two files , let one be main.html which has the main javascript code let it be called main.js , and the other is imported.js
This is the main.html file
<!Doctype html>
<html>
<head>
Dwell time for workers
</head>
<script src = https://requirejs.org/docs/release/2.3.6/r.js></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script type="text/javascript" src="text.json"></script>
<script src="testing_file.js"></script>
<script type = "text/javascript"></script>
<script>
var Import = new import_file('osama'); // constructor
var out = Import.dwell_times()
console.log('out')
console.log(out[2]);
</script>
<body>
<h1> worker time : </h1>
</body>
</html>
This is the imported.js file
var that = null;
class import_file
{
constructor(title)
{
this.title = title;
that = this;
}
dwell_times()
{
console.log('osama')
var x = [5,4,3,2,1] ;
var y = x.toString();
console.log(y)
let parsed = require('./updated.json')
console.log(parsed) ;// Arham
return parsed;
}
}
var Import = new import_file('osama'); // constructor
var out = Import.dwell_times()
console.log('out')
console.log(out[2])
I am getting the following error
Uncaught Error: Module name "updated.json" has not been loaded yet for context: _. Use require([])
https://requirejs.org/docs/errors.html#notloaded
at makeError (r.js:417)
at Object.localRequire [as require] (r.js:1685)
at requirejs (r.js:2046)
at import_file.dwell_times (testing_file.js:16)
at imported.js:23
What do i do to solve this error ?
Require is unable to parse this out and automatically convert it. The solution is to convert to the callback syntax :
var moduleName = './updated.json';
require([moduleName], function(fooModule){
// do something
})
I'm using the getElementByClassName function to change the displayed text.
I'm running into 2 different problems.
Problem 1:
I want to change my <title></title> to the value of var value.
It doesnt work the like the displayed text in the body element.
Problem 2:
Now I'm using 4 different variables because I can only declare a getElementsbyClassName once every class. I there a way to write this code more beautiful/compacter?
Any help would be appricated,
<!DOCTYPE html>
<html lang="">
<head>
<title><!--VALUE HERE<div class="div0"></div>--></title>
</head>
<body>
<div class="div1"></div>
<div class="div2"></div>
<div class="div3"></div>
<script>
var value= "Banana";
//var vartest0 = document.getElementsByClassName("div0");
var vartest1 = document.getElementsByClassName("div1");
var vartest2 = document.getElementsByClassName("div2");
var vartest3 = document.getElementsByClassName("div3");
//vartest0[0].innerHTML = value;
vartest1[0].innerHTML = value;
vartest2[0].innerHTML = value;
vartest3[0].innerHTML = value;
</script>
</body>
</html>
To set the value for title, you need to do document.title = "Banana"; or document.title = value;.
<!DOCTYPE html>
<html lang="">
<head>
<title></title>
</head>
<body>
<div class="div1"></div>
<div class="div2"></div>
<div class="div3"></div>
<script>
var value= "Banana";
document.title = value;
var vartest1 = document.getElementsByClassName("div1");
var vartest2 = document.getElementsByClassName("div2");
var vartest3 = document.getElementsByClassName("div3");
//vartest0[0].innerHTML = value;
vartest1[0].innerHTML = value;
vartest2[0].innerHTML = value;
vartest3[0].innerHTML = value;
</script>
</body>
</html>
I’d suggest:
// use document.querySelectorAll() to retrieve all the elements
document.querySelectorAll(".div1,.div2,.div3")
// use NodeList.forEach() to iterate over all the
// returned Nodes
.forEach(
// using an Arrow function ("el" is a reference to the
// current Node of the NodeList), here we update the
// textContent of each Node to the "value" variable:
(el) => el.textContent = value);
// and set the document.title to that same variable:
document.title = value;
I am trying to write a script that changes the color of the text if it is an active screen (there are probably more efficient ways to do this). The error I am getting is Uncaught TypeError: Cannot set property 'innerHTML' of null My JavaScript (the entire page)
function main() {
var cardDiv = '<div id ="cardScreen"><a href="cardScreen.html">';
var card = "Card";
var closer = "</a></div>";
var color = (function color1(Check) {
if (window.location.href.indexOf(Check))
return "red";
else
return "white";
});
card.fontcolor = color("cardScreen");
var cardDivPrint = cardDiv + card + closer;
window.onload=document.getElementById("header").innerHTML= cardDivPrint;
}
main();
The HTML
<!DOCTYPE html>
<link href="../css/MasterSheet.css" rel="stylesheet" />
<html>
<head>
<title>
</title>
</head>
<body>
<div id="header">
</div>
<div>Content goes here.</div>
<script src="../scripts/essentials.js"></script>
</body>
</html>
The IDE (Visual Studio 2015 Cordova) says that the error is on this line in the JavaScript "var cardDivPrint = cardDiv + card + closer;" I have looked at multiple similar problems and applied what was relevant (also tried changing window.onload to document.onload) but it still throws the same error.
onload expects function to be executed after page is completely loaded. Otherwise it'll treat it as simple assignment statement and execute. Use function as follow:
window.onload = function() {
document.getElementById("header").innerHTML = cardDivPrint;
};
UPDATE
Instead of using main(), use DOMContentLoaded event.
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
var cardDiv = '<div id ="cardScreen"><a href="cardScreen.html">';
var card = "Card";
var closer = "</a></div>";
var color = window.location.href.indexOf(Check) !== -1 ? "red" : "white";
card.fontcolor = color("cardScreen");
var cardDivPrint = cardDiv + card + closer;
document.getElementById("header").innerHTML = cardDivPrint;
});
Call the main function at the end of your body content
You are getting this error just because the element dose not exists at the time of its selection by JS DOM
<!DOCTYPE html>
<html>
<head>
<title>
</title>
<link href="../css/MasterSheet.css" rel="stylesheet" />
<script>
function main() {
var cardDiv = '<div id ="cardScreen"><a href="cardScreen.html">';
var card = "Card";
var closer = "</a></div>";
var color = (function color1(Check) {
if (window.location.href.indexOf(Check))
return "red";
else
return "white";
});
card.fontcolor = color("cardScreen");
var cardDivPrint = cardDiv + card + closer;
window.onload=document.getElementById("header").innerHTML= cardDivPrint;
}
</script>
</head>
<body>
<div id="header">
</div>
<div>Content goes here.</div>
<script>main();</script>
</body>
</html>
Say I have the following JavaScript in a HTML page
<html>
<script>
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
</script>
<body>
<a href = test.html>I need the value of "splitText" variable here</a>
</body>
</html>
How do I get the value of the variable "splitText" outside the script tags.
Thanks!
<html>
<script>
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
window.onload = function() {
//when the document is finished loading, replace everything
//between the <a ...> </a> tags with the value of splitText
document.getElementById("myLink").innerHTML=splitText;
}
</script>
<body>
<a id="myLink" href = test.html></a>
</body>
</html>
Try this :
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
$("#target").text(splitText);
});
</script>
<body>
<a id="target" href = test.html></a>
</body>
</html>
<html>
<head>
<script>
function putText() {
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
document.getElementById("destination").innerHTML = "I need the value of " + splitText + " variable here";
}
</script>
</head>
<body onLoad = putText()>
<a id="destination" href = test.html>I need the value of "splitText" variable here</a>
</body>
</html>
In raw javascript, you'll want to put an id on your anchor tag and do this:
<html>
<script>
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
function insertText(){
document.getElementById('someId').InnerHTML = splitText;}
</script>
<body onload="insertText()">
I need the value of "splitText" variable here
</body>
</html>
Here you go: http://codepen.io/anon/pen/cKflA
Although, I must say that what you are asking to do is not a good way to do it. A good way is this: http://codepen.io/anon/pen/jlkvJ
The info inside the <script> tag is then processed inside it to access other parts. If you want to change the text inside another paragraph, then first give the paragraph an id, then set a variable to it using getElementById([id]) to access it ([id] means the id you gave the paragraph).
Next, use the innerHTML built-in variable with whatever your variable was called and a '.' (dot) to show that it is based on the paragraph. You can set it to whatever you want, but be aware that to set a paragraph to a tag (<...>), then you have to still put it in speech marks.
Example:
<!DOCTYPE html>
<html>
<body>
<!--\|/id here-->
<p id="myText"></p>
<p id="myTextTag"></p>
<script>
<!--Here we retrieve the text and show what we want to write...
var text = document.getElementById("myText");
var tag = document.getElementById("myTextTag");
var toWrite = "Hello"
var toWriteTag = "<a href='https://stackoverflow.com'>Stack Overflow</a>"
<!--...and here we are actually affecting the text.-->
text.innerHTML = toWrite
tag.innerHTML = toWriteTag
</script>
<body>
<html>