I am currently working on implementing a star rating system that displays the rating when a star is clicked.
(Just to clarify, I have multiple similar divs which is why unique IDs are not assigned to each star (span))
HTML:
<div id="rating1" class="rating">
<span>★</span><span>★</span><span>★</span><span>★</span><span>★</span>
</div>
jQuery:
$(document).ready(function(){
$("#rating1 span:nth-child(1)").click(function()
{
if (x == 5)
{
alert("You rated 1 star");
}
if (x == 4)
{
alert("You rated 2 stars");
}
if (x == 3)
{
alert("You rated 3 stars");
}
if (x == 2)
{
alert("You rated 4 stars");
}
if (x == 1)
{
alert("You rated 5 stars");
}
});
});
If you're curious about the reversed numbers in $("#rating1 span:nth-child(1)"), it's due to the CSS styling where preceding stars light up upon hovering over a star. Since only succeeding stars can be highlighted, I had to reverse them using "direction: rtl;".
The issue I'm facing is wanting to replace the static number 1 with a variable X that changes based on the clicked star - i.e., clicking the first star assigns x=5, and so on. As a jQuery novice, I would greatly appreciate a comprehensible answer. The "alert" function is just for testing purposes; ideally, the rating should display below.
If any part is unclear, feel free to inquire so I can update my query. Apologies if it's a bit convoluted; I'm still a beginner in both programming and Stack Overflow.