Friday, October 5, 2012

JavaScript Celsius-Fahrenheit Converter

Your first JavaScript script pops up an alert box. Your second script converts between Celsius and Fahrenheit. So without further ado ... the infamous Celsius-Fahrenheit Converter.

Fahrenheit
Celsius

Source code:

<html>
  <head>
    <title>Temperature Converter</title>
  </head>
  <body>
    <h2>Temperature Converter</h2>
    <hr/>
    <form name="temperature">
      <table>
        <tr>
          <td>Fahrenheit</td>
          <td><input type="text" name="fahrenheit" onchange="ftoc();"></td>
        </tr>
        <tr>
          <td>Celsius</td>
          <td><input type="text" name="celsius" onchange="ctof();"></td>
        </tr>
      </table>
    </form>
    <script language="JavaScript">
      function ftoc() {
        var f = document.temperature.fahrenheit.value;
        if (isNaN(f)) {
            document.temperature.celsius.value = '';
        } else {
            var c = (5.0 / 9.0) * (f - 32);
            document.temperature.celsius.value = c.toFixed(2);
        }
      }

      function ctof() {
        var c = document.temperature.celsius.value;
        if (isNaN(c)) {
            document.temperature.fahrenheit.value = '';
        } else {
            var f = ((9.0 / 5.0) * c) + 32;
            document.temperature.fahrenheit.value = f.toFixed(2);
        }
      }
    </script>
  </body>
</html>

No comments:

Post a Comment