There are two problems (and a couple of other things you probably want to change), but they're not hoisting:
- You're not calling your function.
onclick="calc"
=> onclick="calc()"
. Or better yet, use modern event handling (more below).
div
elements don't have a value
property. You probably want to assign to textContent
.
Also:
- Although
a * 12
will work, because of implicit conversion from string to number, I always recommend explicitly converting from string to number. (a
is a string because you got the value from the value
property of an input
, which is always a string.) You have lots of options; I'll use parseFloat
below.
- You've left out the opening
<html>
tag. Technically, it's optional if you have a <head>
tag, but I suspect you left it out because you thought the <!doctype html>
was the start tag. It isn't, they're separate things (<!doctype html>
is the doctype preamble).
Here's an example using modern event handling rather than onxyz
-attribute event handlers. That lets you keep calc
from being global. The global namespace is really crowded and it's easy to have hard-to-diagnose conflicts:
<!DOCTYPE html>
<html>
<head>
<title>Functions exc. 8</title>
</head>
<body>
Input monthly salary: <input type="text" placeholder="invoer" id="value1"><br>
<button id="btn-calc" type="button">Calculate yearly salary</button> <br>
Output yearly salary:<div id="jaarsalaris"></div>
<script>
// This is a "scoping function"
(function() {
document.getElementById("btn-calc").addEventListener("click", calc);
//calculate the yearly salary
function calc() {
var a = parseFloat(document.getElementById("value1").value);
var calculateMonth = a * 12;
document.getElementById("jaarsalaris").textContent = calculateMonth;// + berekeningVktgeld;
}
})();
</script>
</body>
</html>
Or if your environment supports them (most do these days), use a module:
<!DOCTYPE html>
<html>
<head>
<title>Functions exc. 8</title>
</head>
<body>
Input monthly salary: <input type="text" placeholder="invoer" id="value1"><br>
<button id="btn-calc" type="button">Calculate yearly salary</button> <br>
Output yearly salary:<div id="jaarsalaris"></div>
<script type="module">
document.getElementById("btn-calc").addEventListener("click", calc);
//calculate the yearly salary
function calc() {
var a = parseFloat(document.getElementById("value1").value);
var calculateMonth = a * 12;
document.getElementById("jaarsalaris").value= calculateMonth;// + berekeningVktgeld;
}
</script>
</body>
</html>
Code at the top level of a module is not at global scope (it's at module scope, which is accessible only to code within the module; code outside the module can't use what's declared within a module unless it's export
ed).