I am trying to replace the result of NaN in my calculator result with 0 or the words "No Input Found".
Here is the Javascript Code for the Section.
// Calculator Functions JavaScript STARTS here
function add() {
var num1 = parseFloat(document.getElementById("num1").value);
var num2 = parseFloat(document.getElementById("num2").value);
document.getElementById("result").textContent = num1 + num2;
}
function subtract() {
var num1 = parseFloat(document.getElementById("num1").value);
var num2 = parseFloat(document.getElementById("num2").value);
document.getElementById("result").textContent = num1 - num2;
}
function multiply() {
var num1 = parseFloat(document.getElementById("num1").value);
var num2 = parseFloat(document.getElementById("num2").value);
document.getElementById("result").textContent = num1 * num2;
}
function divide() {
var num1 = parseFloat(document.getElementById("num1").value);
var num2 = parseFloat(document.getElementById("num2").value);
document.getElementById("result").textContent = num1 / num2;
}
// Calculator Functions JavaScript ENDS here
Here is my HTML code for the section.
<div id="container">
<h2>Basic Web Calculator</h2>
<input class="instbtn" type="text" id="num1" placeholder="Enter Numbers Here">
<input class="instbtn" type="text" id="num2" placehodler="Enter Numbers Here">
<br>
<button class="calbtn" onclick="add()">Add (+)</button>
<button class="calbtn" onclick="subtract()">Subtract (-)</button>
<button class="calbtn" onclick="multiply()">Multiply (x)</button>
<button class="calbtn" onclick="divide()">Divide (÷)</button>
<br>
<h3>Result: <span id="result"></span></h3>
</div>
2
Answers
I tried multiple codes and still failed.. until I did the most simplest of things. I added || 0; at the end of the answer code line.
This should do the trick: