Skip to content

Instantly share code, notes, and snippets.

@teisman
Last active January 17, 2024 21:42
Show Gist options
  • Save teisman/4518243 to your computer and use it in GitHub Desktop.
Save teisman/4518243 to your computer and use it in GitHub Desktop.

Setting up a star rating system is easy. First set up a html form as follows.

  <form>
    ...
    <div>
      <i class='icon-star-empty input-rating' data-value='1'></i>
      <i class='icon-star-empty input-rating' data-value='2'></i>
      <i class='icon-star-empty input-rating' data-value='3'></i>
      <i class='icon-star-empty input-rating' data-value='4'></i>
      <i class='icon-star-empty input-rating' data-value='5'></i>
    </div>
    <input id='input-rating' name='rating' type='hidden' value=''>
    ...
  </form>

Note that this snippet uses the icon-star and icon-star-empty classes, which come from Twitter Bootstrap.

Then implement the following javascript function.

  <script type="text/javascript">
    (function() {
      $(document).ready(function() {
        $('.input-rating').click(function() {
          $('#input-rating').val($(this).attr('data-value'));
          $(this).siblings().andSelf().removeClass('icon-star icon-star-empty');
          $(this).prevAll().andSelf().addClass('icon-star');
          $(this).nextAll().addClass('icon-star-empty');
        });
      });
    }).call(this);
  </script>

When a star is clicked, the input element gets the value of the data-value of the star that was clicked. All stars have their icon classes removed. The clicked star and all stars before it are appointed the icon-star class; all stars after the clicked star get the icon-star-empty class.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment