Convert data to images using jQuery / CSS or, possibly, PHP / CSS. (Grade System)

- link removed -

How to convert the numbers on the above website to stars using jQuery with a for loop to add the number of stars and the rounding function down.

I prefer rounding using this example:

  • 3.0, if it is less than 3.25; this will include 3 stars, 2 empty stars
  • 3.5 if between 3.25 and 3.75; this will include 3 full stars and 1 half star, 1 empty star
  • 4.0, if higher than 3.75; it will include 4 stars, 1 empty star
+3
source share
1 answer

You will need to update your rating list in the selected container, and the radius must be encapsulated in its own selector.

HTML:

<ul class="ratings">
  <li>Overall Rating Data (no stars): <span>3.14285714286</span></li>
  <li>Overall Grounds Data (no stars): <span>3.14285714286</span></li>
  <li>Overall Price Data (no stars): <span>3.14285714286</span></li>
  <li>Overall Staff Data (no stars): <span>3</span></li>
  <li>Overall Maintenance Data (no stars): <span>2.85714285714</span></li>
  <li>Overall Noise Data (no stars): <span>3.42857142857</span></li>
  <li>Overall Amenities Data (no stars): <span>3.57142857143</span></li>
  <li>Overall Location Data (no stars): <span>3.28571428571</span></li>
  <li>Overall Parking Data (no stars): <span>3.28571428571</span></li>
  <li>Overall Safety Data (no stars): <span>3</span></li>
</ul>

JS:

$(document).ready(function() {
  $('ul.ratings li').each(function() {
    var $el = $(this);
    var rating = $el.find('span').text();
    var $stars = $('<div><div class="ratings-stars"></div><div class="ratings-stars"></div><div class="ratings-stars"></div><div class="ratings-stars"></div><div class="ratings-stars"></div></div>');
    var full_stars = Math.floor(rating);
    var half_star = false;
    var remainder = rating - full_stars;

    if(remainder >= 0.25 && remainder <= 0.75) {
      half_star = true;
    } else if(remainder > 0.75) {
      full_stars += 1;
    }   

    $stars.find('div:lt('+full_stars+')').addClass('star');
    if(half_star) {
      $stars.find('div:eq('+full_stars+')').addClass('half-star');
    }

    $el.find('span').replaceWith($stars);
  });
});

CSS, .

EDIT: $stars <div /> <span />

+2

All Articles