brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: the output element shows a calculated result that screen readers announce

Web-Development
~/tips/tip-output-element-live-result

Total: € <output name="total" for="qty">9.00</output>

A form result updates in place and is read out without moving focus.

For a small calculator, like a price times a quantity, the result often goes into a span. The output element is made for this and brings accessibility for free.

<form oninput="total.value = (qty.valueAsNumber * 4.5).toFixed(2)">
  <label>Tickets <input type="number" id="qty" name="qty" value="2" min="1"></label>
  Total: &euro; <output name="total" for="qty">9.00</output>
</form>

The for attribute lists the ids of the inputs that feed the result, separated by spaces. Because the output has a name, the form’s oninput handler can reach it directly as total, the same way it reaches qty. Every keystroke updates the total.

The extra I like most: MDN says many browsers treat output as a live region, so a screen reader announces the new total while focus stays in the number field. With a plain span you would have to add aria-live yourself.

The thing that catches people out: the value of an output is not sent when the form is submitted, even though it has a name. That is deliberate. If the server needs the total, calculate it there again, which you should do anyway, since anyone can change the number in their browser.

Further reading: MDN: The output element

More Web-Development tips ab -n 200 -c 10 https://example.com/ console.assert(items.length > 0, 'cart is empty', items) document.designMode = "on" function save(item) { Save draft All Web-Development tips (67) All topics

Link