random1234
random1234

Reputation: 817

Star rating system jquery

I'm trying to make a star rating system, where if you click the star it will show the rating.

(fyi i have multiple of these divs so that is why i have not given each star(span) a unique ID)

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 rate 1 star");
    }
    if (x == 4)
    {
        alert("You rate 2 star");
    }
    if (x == 3)
    {
        alert("You rate 3 star");
    }
    if (x == 2)
    {
        alert("You rate 4 star");
    }
    if (x == 1)
    {
        alert("You rate 5 star");
    }
  });
});

If you are wondering why the numbers are flipped it's because of the css where I made it so that the preceeding stars would light up when you hover over a star, since you can only make the succeeding one light up i had to reverse them using direction:rtl;

Here's the problem, instead of the 1 inside of $("#rating1 span:nth-child(1)") i want to have the variable X and I want X to depend on which one i clicked, if i click the first star x=5 etc. I am new to jQuery and would really appreciate an answer that i could understand. The "alert" is just a test, I actually want it to show the rating underneath.

If anything is unclear, ask and i will update my question, forgive me if it is confusing, I am a beginner, both to programming, and stackoverflow.

Upvotes: 0

Views: 1308

Answers (1)

BrunoLM
BrunoLM

Reputation: 100312

Change

$("#rating1 span:nth-child(1)")

to

$("#rating1 span")

and use .index to get the index of the clicked element:

$("#rating1 span").click(function() {
  var x = $(this).index() + 1;
  alert(x);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="rating1">
  <span>1</span><span>2</span><span>3</span><span>4</span><span>5</span>
</div>

Upvotes: 3

Related Questions