Sadegh Shaikhi
Sadegh Shaikhi

Reputation: 152

Function doesn't work in JS Fahrenheit to Celsius convertor

I wanna to add an input number (in Fahrenheit) and convert it to Celsius degree, but i can't figure out how to do it by a function.

<!DOCTYPE html>
<html>
<body>

<p>This example calls a function to convert from Fahrenheit to Celsius:</p>

<input type="number" id="myInput" placeholder="Enter Fahrenheit degree" />

<button id="myButton" type="button">Convert to Celsius</button>

<p id="demo"></p>

<script>

var fahr = document.getElementById("myInput").value;

function toCelsius(fahr) {
  return (5/9) * (fahr-32);
}

document.getElementById("myButton").onclick = function() {

document.getElementById("demo").innerHTML = toCelsius(fahr);
};

</script>

</body>
</html>

I have tried to do it by a single var like this too:

var fahr = document.getElementById("myInput").value;

var c = (5/9) * (fahr-32);



document.getElementById("myButton").onclick = function() {

document.getElementById("demo").innerHTML = c;
};

but it keeps showing me same result every time in both cases(This number:-17.77777777777778)

Thanks for your help

Upvotes: 0

Views: 191

Answers (3)

dfsq
dfsq

Reputation: 193261

You want to read fahr input value inside of onclick handler. It also makes sense to round returned value to maybe one (or two) decimal numbers:

function toCelsius(fahr) {  
  return ((5 / 9) * (fahr - 32)).toFixed(1);
}

document.getElementById("myButton").onclick = function() {
  var fahr = document.getElementById("myInput").value;
  document.getElementById("demo").innerHTML = toCelsius(fahr);
};
<p>This example calls a function to convert from Fahrenheit to Celsius:</p>
<input type="number" id="myInput" placeholder="Enter Fahrenheit degree" />
<button id="myButton" type="button">Convert to Celsius</button>
<p id="demo"></p>

Upvotes: 2

hyperneutrino
hyperneutrino

Reputation: 5425

fahr returns a string. You must first cast the variable fahr into a number before you can perform arithmetic on it.

var fahr = Integer.parseInt(...);
var c = (5 / 9) * (fahr - 32);

Upvotes: 2

jonathanhuo11
jonathanhuo11

Reputation: 758

fahr returns a string, not an int

Upvotes: 1

Related Questions