Skip to content

Instantly share code, notes, and snippets.

Last active July 25, 2021 23:44
Show Gist options
  • Save w3collective/8b472f79af15ac26ad57567aa7477a68 to your computer and use it in GitHub Desktop.
Save w3collective/8b472f79af15ac26ad57567aa7477a68 to your computer and use it in GitHub Desktop.
3 percentage calculators using JavaScript
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>JavaScript Percentage Calculators</title>
<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" />
<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" />
<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" />
// X is what % of Y?
.addEventListener("click", function (e) {
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?
.addEventListener("click", function (e) {
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?
.addEventListener("click", function (e) {
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;
Copy link

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