Write a JavaScript program to convert temperatures to and from celsius, fahrenheit.
Formula : c/5 = (f - 32)/9 [where c = temperature in celsius and f = temperature in fahrenheit]
Expected output: 60°C is 140°F, 45°F is 7.222222222222222°C.
Enter a temperature value in the desired field to see the coresponding value in the other scale.
°C °F
$(document).ready(function() {
function celsiusToFahrenheit(c) {
return c * 9 / 5 + 32;
}
function fahrenheitToCelsius(f) {
return (f - 32) * 5 / 9;
}
$('.data').on('keyup', 'input', function(event) {
var key = event.which,
temperature = $(this).val().split(' ').join(''); // Don't allow spaces to be entered
if (key === 27 || isNaN(temperature) || temperature === '') {
if (temperature === '') { // If field is empty, reset both fields
$('.celsius').val('');
$('.fahrenheit').val('');
}
return; // On Esc and on entering non number, do nothing
}
temperature = temperature * 1; // Convert temperature string to number
if ($(this).hasClass('celsius') && parseFloat(temperature) === temperature) {
$('.fahrenheit').val(celsiusToFahrenheit(temperature));
} else if ($(this).hasClass('fahrenheit')) {
$('.celsius').val(fahrenheitToCelsius(temperature));
}
});
});