Search code examples
javascripthtmlrating

Star rating with html and javascript is not working in the right order


I attempted to create a star rating system using HTML and JavaScript, but it's not functioning properly.

Instead of working from left to right, it works in the opposite direction - from right to left. For instance, if I click on the fourth star, it will color four stars from right to left instead of left to right, so that the first star remains uncolored.

Can anyone advise on how to correct this issue?

function fillStars(num) {
  for (var i = 1; i <= 5; i++) {
    var star = document.getElementById('star' + i.toString());
    if (i <= num) {
      star.checked = true;
    } else {
      star.checked = false;
    }
  }
}
.rating {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}

.rating input[type="radio"] {
  display: none;
}

.rating label {
  font-size: 60px;
  margin-right: 10px;
  cursor: pointer;
}

.rating label::before {
  content: "\2606";
  display: inline-block;
  width: 1.1em;
  text-align: center;
}

.rating label.checked::before {
  content: "\2605";
  color: gold;
}

.rating label.checked~label::before {
  content: "\2605";
  color: gold;
}

.rating input[type="radio"]:checked {
  content: "\2605";
  color: gold;
}

.rating input[type="radio"]:checked~label::before {
  content: "\2605";
  color: gold;
}
<div class="form-name">
  <fieldset class="rating">
    <legend>Bewertung:</legend>
    <input type="radio" id="star1" name="rating" value="1" onclick="fillStars(1)" />
    <label for="star1" title="1 Stern"></label>
    <input type="radio" id="star2" name="rating" value="2" onclick="fillStars(2)" />
    <label for="star2" title="2 Sterne"></label>
    <input type="radio" id="star3" name="rating" value="3" onclick="fillStars(3)" />
    <label for="star3" title="3 Sterne"></label>
    <input type="radio" id="star4" name="rating" value="4" onclick="fillStars(4)" />
    <label for="star4" title="4 Sterne"></label>
    <input type="radio" id="star5" name="rating" value="5" onclick="fillStars(5)" />
    <label for="star5" title="5 Sterne"></label>
  </fieldset>
</div>


Solution

  • Please replace below code in css:

    .rating {
      display: flex;
      flex-direction: row-reverse;
      justify-content: center;
      align-items: center;
    }

    Hope this will solve your problem.