Skip to content

Instantly share code, notes, and snippets.

@pk
Created January 27, 2021 08:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pk/f88c1223a23d6396b91a5611df2acd49 to your computer and use it in GitHub Desktop.
Save pk/f88c1223a23d6396b91a5611df2acd49 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
.feld1 {
margin: 20px;
}
.feld2 {
margin: 20px;
}
</style>
<script>
function getFieldValue(field) {
const element = document.getElementById(field);
return parseInt(element.value);
}
function updateResultElement(value) {
const element = document.getElementById("ergebnis");
element.value = value;
}
function plus() {
var summe = getFieldValue("feld1") + getFieldValue("feld2");
updateResultElement(summe);
}
function minus() {
var differenz = getFieldValue("feld1") - getFieldValue("feld2");
updateResultElement(differenz);
}
function mal() {
var produkt = getFieldValue("feld1") * getFieldValue("feld2");
updateResultElement(produkt);
}
function dividiert() {
var quotient = getFieldValue("feld1") / getFieldValue("feld2");
updateResultElement(quotient);
}
</script>
</head>
<body>
<center>
<h1>Taschenrechner</h1>
<p>
Eingabefeld 1: <input id="feld1" type="number" />
<br>
<br>
Eingabefeld 2: <input id="feld2" type="number" />
<br>
<br>
<button class="plus" onclick="plus()">+</button>
<button class="minus" onclick="minus()"> - </button>
<button class="mal" onclick="mal()"> * </button>
<button class="dividiert" onclick="dividiert()"> / </button>
<br>
<br>
Ergebnis: <input id="ergebnis" type="number" readonly />
</center>
</body>
</html>
@pk
Copy link
Author

pk commented Jan 27, 2021

So few changes

  • It's not C so things like int won't apply here, it's dynamically typed
  • You can't just get elements in the HEAD as those elements don't exist yet. You'd need to move the script down just before the /body or just use functions to get the values when you press the buttons as I did.
  • Inputs are giving you strings... despite the type is number so parseInt() is necessary

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment