SyntaxStudy
Sign Up
jQuery Intermediate 4 min read

Interactive Star Rating

Star Rating Widget

Build a clickable star rating that previews on hover and saves on click.

Example
$(function() {
  const $stars = $(".rating .star");
  $stars.on("mouseenter", function() {
    const val = +$(this).data("value");
    $stars.each(function(i) { $(this).toggleClass("filled", i < val); });
  }).on("mouseleave", function() {
    const current = $("#rating-value").val() || 0;
    $stars.each(function(i) { $(this).toggleClass("filled", i < current); });
  }).on("click", function() {
    const val = +$(this).data("value");
    $("#rating-value").val(val);
    $.post("/api/rate", { rating: val, id: $(this).closest("[data-id]").data("id") });
  });
});
Pro Tip

Store the current rating in a hidden input — makes the value accessible to the form on submit.