← Web basics: HTML, CSS and JavaScript
Typing: input events and values
Read what people type with .value and react as they type.
Form fields have a value property holding what is typed in them. The input event fires every time the value changes, so a listener on it can update the page live, letter by letter. One thing to remember: value is always a string, even in a number box. To do math with it, convert it with Number(). An empty box gives the empty string "".
<label for="km">Kilometres</label>
<input id="km" type="number">
<p id="out"></p>
<script>
const km = document.querySelector("#km");
const out = document.querySelector("#out");
km.addEventListener("input", () => {
const miles = Number(km.value) * 0.621;
out.textContent = miles.toFixed(1) + " miles";
});
</script>Each time the number changes, the handler reads km.value (a string), turns it into a number, converts it and shows the result with one decimal.
The change event is similar but fires less often: for text boxes, only when the person leaves the box. For checkboxes and drop-downs, change is the usual choice.
For checkboxes, read .checked (true or false) instead of .value.