Search code examples
phpjquerycssimagerating-system

Converting data to images using JQuery/CSS or possibly PHP/CSS. (Rating System)


-- link removed --

How can I convert the numbers in the above website into stars using Jquery with a for loop to add however many stars, and a round up, round down function.

I prefer to round using this example:

  • 3.0 if lower than 3.25; this will include 3 full 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 higherthan 3.75; this will include 4 full stars, 1 empty star

Solution

  • You would need to update your list of ratings to be in a selectable container, and the rading would need to be encapsulated in it's 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);
      });
    });
    

    The CSS I'll leave up to you.

    EDIT: Updated $stars to use <div /> instead of <span />