Antonio Gvardijan
Antonio Gvardijan

Reputation: 25

Testing if entered value is a number

I had a task to enter a °F and convert it to °C. I also has to show a error messege instead of a number if entered value is not a number. What ever I do I can't get it to work properly. When I type letter it just shows -17.77777777777778 °C instead of messege. Can I get some help from you ?

function temperatura(){
  var temp = document.getElementById("tempF").value;
  if (isNaN(temp)){
    document.getElementById("demo2").innerHTML =
    "You need to enter a number!";
  } else {
    document.getElementById("demo2").innerHTML = uCelzije(temp)+" °C";
  }
}
function uCelzije(f){
  return (5/9) * ( Number(f) - 32 );
}
 

<p>Enter Fahrenheit to convert it to Celsius.</p>
<form>
  <input type="number" id="tempF">°F
</form>
<button onclick="temperatura()">Try it</button>
<p id="demo2"></p><br>

Upvotes: 0

Views: 56

Answers (3)

10100111001
10100111001

Reputation: 1832

You need to parse the temp value as int. This will make sure that temp is either a number or NaN. Everything will work just fine.

Edit: This was suggested by @Servuc as well in the question comments.

<p>Enter Fahrenheit to convert it to Celsius.</p>
<form>
  <input type="number" id="tempF">°F
</form>
<button onclick="temperatura()">Try it</button>
<p id="demo2"></p>
<br>
<script>
  function temperatura() {
    var temp = parseInt(document.getElementById("tempF").value);
    if (isNaN(temp)) {
      document.getElementById("demo2").innerHTML =
        "You need to enter a number!";
    } else {
      document.getElementById("demo2").innerHTML = uCelzije(temp) + " °C";
    }
  }

  function uCelzije(f) {
    return (5 / 9) * (Number(f) - 32);
  }
</script>

Upvotes: 0

luiseliberal
luiseliberal

Reputation: 1

Antonio, if i understood well, maybe you only need to add a new validation to check an empty string, following how you construct your code. Try to add an empty string validation to your script.

var temp = document.getElementById("tempF").value;
    if (isNaN(temp) || temp.trim() == ""){
      document.getElementById("demo2").innerHTML =
      "You need to enter a number!";
    } else {
      document.getElementById("demo2").innerHTML = uCelzije(temp)+" °C";
    }

Upvotes: 0

madox2
madox2

Reputation: 51841

It's because your input is type of number. If you type a letter, this value is not accepted and it remains an empty string:

isNaN(''); // false

then this empty string is converted to 0 in your uCelzije function:

(5/9) * ( 0 - 32 ); // -17.77777777777778

so you should also check if the input isn't empty, e.g.:

if (temp == '' || isNaN(temp)){

Upvotes: 1

Related Questions