JSFiddle - React, Tailwind, and code Playground
by gweax
HTML
<form>
<h1>Convert temperatures</h1>
<label>
Celsius
<input name="celsius" type="number" min="-273.15" step="any" data-from="x" data-to="x">
</label>
<label>
Kelvin
<input name="kelvin" type="number" min="0" step="any" data-from="x - 273.15" data-to="x + 273.15">
</label>
<label>
Fahrenheit
<input name="fahrenheit" type="number" min="-459.67" step="any" data-from="(x - 32) * 5 / 9" data-to="x / 5 * 9 + 32">
</label>
</form>
CSS
label {
display: block;
margin-bottom: 1em;
}
input {
display: block;
min-width: 200px;
}
JavaScript
function calculate(event) {
var target = event.target,
form = target.form,
value = target.valueAsNumber,
from = new Function('x', 'return ' + target.getAttribute('data-from')),
baseValue = from(value);
Array.from(form.querySelectorAll('input'))
.filter(function(input) {
return input !== target;
})
.forEach(function(input) {
var to = new Function('x', 'return ' + input.getAttribute('data-to'));
input.value = to(baseValue).toFixed(2);
});
}
var form = document.querySelector('form');
form.addEventListener('change', calculate);
form.addEventListener('keyup', calculate);