Convert Fahrenheit to Celsius

Hosmer23 0 Tallied Votes 142 Views Share

A simple HTML code that converts Fahrenheit to Celsius and Vice Versa.

<font size=+1>Enter a number in either field, then click outside
the text box.&nbsp;<form>F:&nbsp;</font><input type="text" name="F" value="32"
    onChange="C.value = 100/(212-32) * (this.value - 32 )">
<br><font size=+1>C:&nbsp;</font><input type="text" name="C" value="0"
    onChange="F.value = (212-32)/100 * this.value + 32 ">
<center></form>

Dani AI

Generated

Good start, . The sample shows the basic math, but it mixes presentation and script (deprecated <font> and inline event handlers) and lacks accessibility, validation, and mobile-friendly input handling. A small refactor improves robustness, keyboard/mobile UX, and maintainability.

Recommended pattern: semantic labels + type="number" with step="any" and inputmode="decimal" for mobile keyboards, keep JS out of HTML, validate with parseFloat/Number.isFinite, and prevent update loops by tracking the active input. Round only for display (e.g., toFixed(2)) so calculations keep full precision. Add an aria-live region or visible result for screen readers.

A compact, modern example:

<form id="temp-converter" onsubmit="return false;">
  <label for="f">Fahrenheit</label>
  <input id="f" type="number" step="any" inputmode="decimal">

  <label for="c">Celsius</label>
  <input id="c" type="number" step="any" inputmode="decimal">

  <div id="announce" aria-live="polite"></div>
</form>

<script>
const f = document.getElementById('f');
const c = document.getElementById('c');
let active = null;

f.addEventListener('focus', () => active = 'f');
c.addEventListener('focus', () => active = 'c');

function toC(v){ return (v - 32) * 5 / 9; }
function toF(v){ return v * 9 / 5 + 32; }

[f, c].forEach(el => el.addEventListener('input', () => {
  const v = parseFloat(el.value && el.value.replace(',', '.'));
  if (!Number.isFinite(v)) { if (active === 'f') c.value = ''; else f.value = ''; return; }
  if (active === 'f') c.value = toC(v).toFixed(2); else f.value = toF(v).toFixed(2);
}));
</script>

Quick tips: accept comma decimal by replacing , with ., prefer input for instant feedback but change to avoid frequent reflows, and ensure the form does not submit on Enter.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.