'How to add text to HTML input field on conditional statements using JavaScript?
I am building a percentage calculator and one of the features is displaying decrease/increase between two numbers. For example, if the user inputs 60 as the first num and 40 as the second, my code displays -33.33 but I also want it to display, in text, that there is an increase/decrease of "x" amount between numbers, depending on what the user has entered. Here's what my code looks like:
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.toFixed(2);
});
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.toFixed(2);
});
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.toFixed(2);
function percentDiffer () {
if (numX > numY) {
}
}
});
}
Solution 1:[1]
Use basic mathematics operations like this:
function percentDiffer (numX, numY) {
if (numX > numY) {
return numX-numY;
} else if (numY > numX) {
return numY-numX;
} else if (numX == numY) {
return 0;
}
}
console.log(percentDiffer(10, 100));
console.log(percentDiffer(100, 10));
console.log(percentDiffer(10, 10));
Solution 2:[2]
Here's my take on this:
document.getElementById("IncreseorDecrese").value = percDiff() //the id is just for reference
function percDiff(){
let result;
if (percentage > 0){
result = 'increased of ' + percentage;
} else{
result = 'decreased of ' + percentage;
}
return result
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | pepeD |
| Solution 2 | Edoardo Balducci |
