JSJunkie JSJunkie - 7 months ago 13
Javascript Question

Simple JS calculator - Why isn't this if statement working?

I decided to post this as a separate question since the topic is slightly different than my original post. I'm trying to build a simple calculator which converts human years into dog years. Users are asked to enter their age into a form. Then they click a button and their age in dog years is displayed beneath the form.

That's all working fine, but I'm trying now to add an if statement to prevent the form from being submitted with a blank string or the number 0. Presently, if someone enters the form with a blank string or zero and then clicks the button, they are told that they are 0 in dog years. Instead, I'd like a message to appear (same place, under the form) which instructs users to enter their age.

Here is the code I have so far:

HTML:

<div id="calculator">
<form>
<p>
<label>What is your current age in human years?</p>
<p><input type="text" id="humanYears"></label></p>
<p>
<button type="button" id="calculate">Calculate</button></p>
<p>
<span id="answer"></span>
</p>
</form>
</div>


JS:

function calculateAge() {
var humanYears = document.getElementById("humanYears").value;
if (humanYears === 0 || "") {
document.getElementById("answer").innerHTML = "Please enter your age in human years.";
return;
}

var dogYears=humanYears * 7;

document.getElementById("answer").innerHTML = "That means you are " + dogYears + " in dog years!";
}

document.getElementById("calculate").onclick = function() { calculateAge(); };


Any help would be greatly appreciated.

Answer

When using the or operator || you still need to add the full expression on both sides, also you need to put the number 0 in quotes, as it is treated like a string like so:

Working example

if (humanYears === "0" || humanYears === "") {
  document.getElementById("answer").innerHTML = "Please enter your age in human years.";
  return;
}