Antonio Gvardijan Antonio Gvardijan - 1 year ago 56
HTML Question

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>
<input type="number" id="tempF">°F
<button onclick="temperatura()">Try it</button>
<p id="demo2"></p><br>

Answer Source

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)){