Skip to content
jshacks.dev
Browser

Build a star rating input

Build a star rating from radio inputs, so the browser handles the arrow keys, grouping and form submission, and CSS draws the stars.

1 min read
Summarize in AI

A star rating is a group of radio buttons that looks different. Using real radios gives you keyboard support, form submission and screen reader labels without ARIA.

rating.htmlHTML
<fieldset class="rating">
  <legend>Rate this post</legend>
  <label><input type="radio" name="stars" value="1"> 1 star</label>
  <label><input type="radio" name="stars" value="2"> 2 stars</label>
  <label><input type="radio" name="stars" value="3"> 3 stars</label>
  <label><input type="radio" name="stars" value="4"> 4 stars</label>
  <label><input type="radio" name="stars" value="5"> 5 stars</label>
</fieldset>
rating.jsJavaScript
document.querySelector('.rating').addEventListener('change', (event) => {
  console.log(`rating: ${event.target.value}`);
});
Text
rating: 4

Radios with the same name form a group, so arrow keys move the selection and exactly one value is submitted. The change event bubbles to the fieldset, so one listener covers all five. Hide the circles and style the label text with CSS, and keep the visible text for screen readers rather than removing it with display: none, which would also take the input out of the tab order.

Use FormData to read the value on submit. The group semantics come from the radio input type.

Share

More snippets

APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read
Browser

Find the closest ancestor with closest

Walk up from an element to the nearest ancestor that matches a selector with closest, which includes the element itself. Works in all modern browsers.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.