Celsius To Fahrenheit

In this example , we will test a simple algorithms to convert temperature in Celsius to Fahrenheit and display on a HTML page.

Advertisements

The step to convert from Celsius to Fahrenheit is given below.

Advertisements
  • Receive input from a HTML text box.
  • When user click the button to convert Celsius to Fahrenheit, execute JavaScript function –convertToFahrenheit().
  • The function uses the formula: F = (Celsius * 9/5) + 32 to convert Celsius to Fahrenheit.
  • The function then output the result to an H1 tag for display.

JavaScript Code: Celsius To Fahrenheit

function convertToF() {
let celsius = document.getElementById("inp").value;
  let fahrenheit = (celsius * 9/5) + 32;
  document.getElementById("demo").innerHTML = fahrenheit + "°F";
}

The function uses the id attribute of HTML element to access the input and print the output in the above program. The rest of the code is to compute the Fahrenheit value.

The entire HTML code and JavaScript code for the program is given below. We also put some CSS code so that the input elements appear nice. You can learn more about the HTML form elements from our HTML tutorial.

HTML and JavaScript Code: Celsius to Fahrenheit

<!DOCTYPE html>
<html>
<head>
    <title>Celcius To Fahrenheit</title>
    <meta charset="utf-8">
</head>
<body>
    <h1 id="demo">Output here</h1>
    <input type="text" id="inp" value="enter celsius"/>
    <button onclick="convertToFahrenheit()">Convert</button>
    <script>
       function convertToFahrenheit() {
          let celsius = document.getElementById("inp").value;
          let fahrenheit = (celsius * 9/5) + 32;
          document.getElementById("demo").innerHTML = fahrenheit + "°F";
        }
    </script>
</body>
</html>

Output To Browser: Celsius to Fahrenheit

Output - Celsius To Fahrenheit Conversion
Output – Celsius To Fahrenheit Conversion

Advertisements

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.