Star Rating Widget
Build a clickable star rating that previews on hover and saves on click.
Build a clickable star rating that previews on hover and saves on click.
$(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") });
});
});
Store the current rating in a hidden input — makes the value accessible to the form on submit.