Celsius and Fahrenheit Converter- JavaScript

convert celsius to fahrenheit javascript freecodecamp
javascript temperature converter code
fahrenheit to celsius java code
javascript converter
code to convert celsius to fahrenheit
celsius to fahrenheit formula
degree celsius in js
how to convert kelvin to fahrenheit jquery

I want to make a webpage that has two text boxes, a Celsius and Fahrenheit box. In between them, there is a convert button which converts Celsius to Fahrenheit and Fahrenheit to Celsius. If there is letters in either box, I want to cancel the converting and an alert pop up saying "Only numbers please!" So far, I haven't figured out how to get the alert and when I type numbers in the Celsius box, it always says the number -18 in the same box. Fahrenheit is fine.

HTML:

<html>
<head>
  <title>Temparature Converter</title>
  <script type="text/javascript" src="tempconversion.js"></script>
</head>
<body>
  Celsius: <input id="c" onkeyup="convert('C')">
  <button type="button" id="convert" onclick="convertTemp()">Convert</button>
  Fahrenheit: <input id="f" onkeyup="convert('F')">
</body>
</html>

JavaScript:

function convertTemp(degree) {
  if (degree == "C") {
    F = document.getElementById("c").value * 9 / 5 + 32;
    document.getElementById("f").value = Math.round(F);
  } else {
    C = (document.getElementById("f").value -32) * 5 / 9;
    document.getElementById("c").value = Math.round(C);
  }
}

Note: I got some code from W3Schools so I think the onkeyup convert is a little funny. If possible, please notify me how it has to change as well as the JavaScript.

There is no need for the onkeyup attributes, since they original code from W3Schools was designed to instantly update values as they were entered.

I did modify the functionality to clear of original value, that way the conversion button can work both ways with a simple code.

Here's a quick JavaScript to do the job:

function convertTemp() {
 // Set the initial variables for c (Celsius) and f (Fahrenheit)
 var c = document.getElementById('c'), f = document.getElementById('f');
 // Test if there is a value for Celsius
 if(c.value != '') {
  // Set the value for Fahrenheit
  f.value = Math.round(c.value * 9 / 5 + 32);
  // Clear the value for Celsius
  c.value = '';
 // If there isn't a value for Celsius
 } else  {
  // Set the value for Celsius
  c.value = Math.round((f.value - 32) * 5 / 9);
  // Clear the value for Fahrenheit
  f.value = '';
 }
}

And its accompanying HTML:

Celcius:<input id="c">&nbsp;&nbsp;&nbsp;
Fahrenheit:<input id="f">&nbsp;&nbsp;&nbsp;
<button type="button" id="convert" onclick="convertTemp()">Convert</button>

It can be tested at: http://jsfiddle.net/bhz6uz54/

Something to remember about simple code, like this, there is nothing to verify the supplied values are acceptable. A little regex can act as validation, but how it would be implemented depends on how you want to flag the problem.

Temperature Converter. Type a value in any of the fields to convert between temperature measurements: Fahrenheit. Celsius. Kelvin  Today we are going to learn how to convert Fahrenheit to Celsius using JavaScript. We mostly use Fahrenheit and centigrade as the two temperature scales in our daily life. Daniel Gabriel Fahrenheit developed the Fahrenheit scale. Here water freezes at 32 degrees and boils at 212 degrees. Swedish astronomer Andres Celsius developed the centigrade scale.

I personally hate Do-it Buttons so I'd go with a more dynamic solution:

// Get the Input elements:
var $f = document.getElementById("f");
var $c = document.getElementById("c");

function FC_CF() {

  var temp;  // Will hold the temperature value
  var $targ; // Used to target the element we're not typing into:

  if (this.id === "c") { // If we're typing into #c...
    $targ = $f;          // use #f as target element
    temp = (this.value * 9 / 5) + 32;  // C2F
  } else {
    $targ = $c;
    temp = (this.value - 32) * 5 / 9;  // F2C
  }

  // Write the result "as we type" in the other ($targ) field:
  $targ.value = !isNaN(temp) ? parseFloat(temp.toFixed(1))  : "Err";
  // (Above:) temp is a num  ? return floated number,   else: "Show some error"

}

// Assign input listeners to trigger the above function:
$f.oninput = FC_CF; 
$c.oninput = FC_CF;
Celcius:    <input id="c">
Fahrenheit: <input id="f">

<h2>JavaScript Celcius to Fahrenhet</h2> ​ <p>Insert a number into one of the input fields below:</p> ​ <p><input id="c" onkeyup="convert('C')"> degrees  Degrees Celsius Degrees Fahrenheit This JavaScript is designed to allow people visiting your web page to do their own little calculation/math assignment right on your web page.

You can separate the functions which do the temperature conversion as follows i did somw changes in the code.

       <p>
    <label>Fahrenheit</label>
  <input id="outputFahrenheit" type="number" placeholder="Fahrenheit"
  oninput="temperatureConverterCelsius(this.value)"
  onchange="temperatureConverterCelsius(this.value)" value="">
</p>
<p>Celsius: </p>

<input id="outputCelsius" type="number" placeholder="Celsius" 
   oninput="temperatureConverterFahrenheit(this.value)" 
    onchange="temperatureConverterFahrenheit(this.value)" value="">
    </p>


    <script type=""text/javascript>
    function temperatureConverterCelsius(valNum) {
    valNum = parseFloat(valNum);
    document.getElementById("outputCelsius").value = (valNum-32) / 1.8;
    //document.getElementById("outputFahrenheit").value = (valNum*1.8)+32;

}
    </script>


  </body>
</html>

Converting a temperature from Celsius to Fahrenheit is a common calculation. It's a good place to start when learning about algorithms  So basically the formula for finding the Celsius is very simple, c = ( f – 32 ) x 5 / 9. c – celsius f – fahrenheit. Pass the Fahrenheit value to the formula, so it will give us the Celsius value. Here is the entire program (1st method, allows any character in the text box):

class Temperature_conversation {

    constructor(celsius) {

        this.celsius= celsius;
        this.fahrenheit= 0;
        this.table_begin= -50.0;
        this.table_end= 50.0;
        this.table_step= 10.0;
        console.log('---------------------Conversion--------------------------');
        console.log('Celsius fahrenheit');
        for(this.celsius = this.table_begin; this.celsius <= this.table_end; this.celsius += this.table_step){
            this.fahrenheit = this.celsiusToFahrenhit(celsius);
        }


    }
    celsiusToFahrenhit(c){
        const minimun_celsius = -273.15;
        if (c < minimun_celsius) {
            throw 'O argumento es pequeno';

        }
         this.celsius = (9.0 / 5.0) * c+ 32;

        var res = [this.celsius, this.fahrenheit]
        console.table(res);
    }
}

WHAT I HAVE SO FAR function convertToF(celsius) { var fahrenheit; // Only change code below this line celsius *= 9/5; celsius += 32; // Only change code above  In between them, there is a convert button which converts Celsius to Fahrenheit and Fahrenheit to Celsius. If there is letters in either box, I want to cancel the converting and an alert pop up saying "Only numbers please!"

There is no need for the onkeyup attributes, since they original code from W3Schools was designed to instantly update values as they were entered. I did modify  Convert from Celsius to Fahrenheit ℉=(℃*1.8)+32: Try it: Convert from Celsius to Kelvin: K=℃+273.15: Try it

This is a basic javascript program which covers the use of edit text box and button combined Duration: 5:51 Posted: Jan 25, 2015 Save Your Code. If you click the save button, your code will be saved, and you get an URL you can share with others.

Example. Celsius: Fahrenheit: Kelvin: Code. Put this in the head part of the document. <script language="JavaScript"> <!-- function CelsiusConverter(){  Java Program to convert Fahrenheit to Celsius – Here we discuss the various methods to convert the Fahrenheit temperature measurement to Celsius temperature measurement and vice versa. The various methods include Static Method, Switch Case and the method. We have added the compiler to each case with sample outputs citing specific examples. The following program

Comments
  • Values obtained from HTML inputs are type string, so you're doing math with strings, just a heads up. Also, you should look up how to abstract your event handling from the HTML. It's a bad practice to use.
  • @SterlingArcher - Since JavaScript is a weakly typed language, there is no problem doing math with strings (except +).
  • @Derek朕會功夫 not to nitpick, but seeing as + is a very standard math operator, there indeed can be a problem with math and strings? I feel it's just safer to typecast so that you don't run a risk of concatenated numbers or NaN results
  • If you click on convert, you call the function with no argument. It automaticly goes in the else part. If the right box is empty, it mean it is 0 so (0 - 32) * 5 / 9 is -17.777777.
  • @SterlingArcher - Well of course strings should always be parsed and fool-proofed before using them. But since there is only * and - operations going on in OP's code, I don't see any issue ignoring all the troublesome parsing and foolproof part, at least for a beginner that is.
  • From the question OP asked, we can clearly see he is in a learning phase. It would be a good idea to explain this code.... Just saying!
  • @Karl-AndréGagnon I agree... I just need some more time to write it all... be patient with me ;)
  • Typically it's probably better to stick to the lib (or lack of lib) the OP is using. Native JS would be a better answer than a jQuery answer here (way overhead for math)
  • I have to agree with Sterling Archer, jQuery is likely going to be too much. I've provided a JavaScript solution that should be easier to understand for beginners.