Citra45Abadi Citra45Abadi - 6 months ago 13
HTML Question

store data from input form to var for javascript function

Hi I am learning javascript right now.
so I want to make a function that converts fahrenheit to celsius but with an input to store in variable and then shows the result with

alert(result);


here's my code from my basic understanding

<p>calls a function to convert from Fahrenheit to Celsius:</p>
<form>
input fahrenheit :<input type="number" id="fa"/>
<button onclick="toCelsius(f)">submit</button>
</form>

<script>
var f = document.getElementById("fa").value;

function toCelsius(f) {
var result = (5/9) * (f-32);
alert (result);
}

</script>


everytime I input a number, the result does not change, I assume I'm wrong in .value or .innerHTML ?

Answer

You need to use the variable, 'f' in your mathematical expression as a number. JavaScript will do type juggling for you, but since you are learning, it is good to know that there is a way to force it.

  function toCelsius() 
  {

       var f = parseFloat(document.getElementById("fa").value);
       var result = (5/9) * (f-32);
       alert (result);
  }

or

  function toCelsius() 
  {
       var result = (5/9) * (parseFloat(document.getElementById("fa").value) - 32);
       alert (result);
  }

or

  function toCelsius() 
  {
       alert ((5/9) * (parseFloat(document.getElementById("fa").value) - 32));
  }

=========

  <button onclick="toCelsius(f)">submit</button>

This won't work because f is not in play at this time. Call your handler, then grab the DOM values you need.

Comments