Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
3 percentage calculators using JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>JavaScript Percentage Calculators</title>
</head>
<body>
<h3>X is what % of Y?</h3>
<form id="calc1">
<input id="calc1-num-x" type="number" /> is what percent of
<input id="calc1-num-y" type="number" /> ?
<input id="calc1-submit" type="submit" value="Calculate" />
<input id="calc1-solution" type="number" readonly="readonly" />
</form>
<h3>What is X% of Y?</h3>
<form id="calc2">
What is <input id="calc2-num-x" type="number" /> % of
<input id="calc2-num-y" type="number" /> ?
<input id="calc2-submit" type="submit" value="Calculate" />
<input id="calc2-solution" type="number" readonly="readonly" />
</form>
<h3>What is the percentage increase or decrease?</h3>
<form id="calc3">
What is the percentage increase or decrease from
<input id="calc3-num-x" type="number" /> to
<input id="calc3-num-y" type="number" /> ?
<input id="calc3-submit" type="submit" value="Calculate" />
<input id="calc3-solution" type="number" readonly="readonly" />
</form>
<script>
// X is what % of Y?
document.getElementById("calc1-submit")
.addEventListener("click", function (e) {
e.preventDefault();
const numX = document.getElementById("calc1-num-x").value;
const numY = document.getElementById("calc1-num-y").value;
const percentage = (numX / numY) * 100;
document.getElementById("calc1-solution").value = percentage;
});
// What is X% of Y?
document.getElementById("calc2-submit")
.addEventListener("click", function (e) {
e.preventDefault();
const numX = document.getElementById("calc2-num-x").value;
const numY = document.getElementById("calc2-num-y").value;
const percentage = (numX / 100) * numY;
document.getElementById("calc2-solution").value = percentage;
});
// What is the percentage increase or decrease?
document.getElementById("calc3-submit")
.addEventListener("click", function (e) {
e.preventDefault();
const numX = document.getElementById("calc3-num-x").value;
const numY = document.getElementById("calc3-num-y").value;
const percentage = (numY - numX) / numX * 100;
document.getElementById("calc3-solution").value = percentage;
});
</script>
</body>
</html>
@w3collective

This comment has been minimized.

Copy link
Owner Author

@w3collective w3collective commented Jul 25, 2021

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