I have to program a calculator for my class. I am not very good at this, so I did it exactly like we did it in class but it is not working and I can't find the problem. I am not looking for the whole solution, just for a tip where the problem is.
The calculator consists of 2 input fields for the numbers and 1 button to add the numbers
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="node_modules"></script>
<script src="script.js"></script>
</head>
<body>
<label for="zahl1"></label>
<input id="zahl1" type="text" placeholder="Zahl eingeben">
<label for="zahl2" type="text"></label>
<input id="zahl2" type="text" placeholder="Zahl eingeben">
<button id="plusBtn" > </button>
<p id="ergebnis"></p>
</body>
</html>
Typescript
document.addEventListener("DomContentLoaded", () => {
document.getElementById("plusBtn").addEventListener("click", () => {
const zahl1Input = document.getElementById("zahl1") as HTMLInputElement;
const zahl2Input = document.getElementById("zahl2") as HTMLInputElement;
const zahl1: number = Number(zahl1Input.value);
const zahl2: number = Number(zahl2Input.value);
const sum = zahl1 zahl2
let ergebnis: number;
ergebnis = sum(zahl1, zahl2)
const ergebnisInput = document.getElementById("ergebnis") as HTMLInputElement;
ergebnisInput.value = ergebnis.toString();
})
})
CodePudding user response:
I fixed the code. Compare the differences...
window.addEventListener("DOMContentLoaded", () => {
document.getElementById("plusBtn").addEventListener("click", () => {
const zahl1Input = document.getElementById("zahl1");
const zahl2Input = document.getElementById("zahl2");
const zahl1 = Number(zahl1Input.value);
const zahl2 = Number(zahl2Input.value);
const sum = zahl1 zahl2
let ergebnis;
ergebnis = sum
const ergebnisInput = document.getElementById("ergebnis");
ergebnisInput.innerText = ergebnis.toString();
})
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="node_modules"></script>
<script src="script.js"></script>
</head>
<body>
<label for="zahl1"></label>
<input id="zahl1" type="text" placeholder="Zahl eingeben">
<label for="zahl2" type="text"></label>
<input id="zahl2" type="text" placeholder="Zahl eingeben">
<button id="plusBtn" > </button>
<p id="ergebnis"></p>
</body>
</html>
CodePudding user response:
ergebnis = sum(zahl1, zahl2)
The problem is here. Using sum(arguments) means you're calling a function called 'sum', but you have not made 'sum' a function but rather a variable containing the sum.
Correct way would be:
ergebnis = sum
This would work, but you can optimize the code further omitting unnecessary variables.