Star Rating Plugin for jQuery

What

An easy to use rating control. It takes a normal select box, and turns it into a rating that your users can click on. The select box is preserved so you can still bind on change, get, and set the value in the rating control. The image is controlled with CSS and a simple gif, so you can make it look like anything you need.

Download

Download (Moved to GitHub)
Download

Example

Here is a sample default rating control with no options.

Source

<select class="rating">
    <option value="0">Did not like</option>
    <option value="1">Ok</option>
    <option value="2" selected="selected">Liked</option>
    <option value="3">Loved!</option>
</select>
$(".rating").rating();

That’s it!

The select box is now replaced with the rating control. Each option you put in the select box is turned into a star, so you can easily have as many stars as you want. The value you set is the value that is returned for the selected star. The text becomes the title on the star.

You can turn the cancel button on and off, and change the value of the cancel button by passing it when you create the rating control.
$(".rating").rating({showCancel: true, cancelValue: null,})

You can make the control readonly by setting <select disabled="disabled">

Available Options:

  • showCancel: true : Should the cancel button be shown?
  • cancelValue: null : If cancel button is shown, what should it’s value be?
  • startValue: null : If no property has the ‘selected’ attribute, what value should be displayed?

Get Value

Click for Value

Source

<select name="myRating" class="rating" id="serialStar">
    <option value="0">Did not like</option>
    <option value="1">Ok</option>
    <option value="2">Liked</option>
    <option value="3">Loved!</option>
</select>
<span id="seralString">Click for Value</span>
<button onclick="$('#seralString').text( $('#serialStar').val() );">Serialize</button>
//Turn the Select into a rating
$(".rating").rating();
//Action on button click
$('#seralString').text( $('#serialStar').val() );

Bind $.serialize() On Change

Of course you don’t have to call $.serialize() here, you can call anything you want. It’s just a normal event. You even have access to the value with $("#serialStar2").val()!

Just click and I’ll change.

Source

<select name="myRating" class="rating" id="serialStar2">
    <option value="1">ALrighte</option>
    <option value="2">Ok</option>
    <option value="3">Getting Better</option>
    <option value="4">Pretty Good</option>
	<option value="5">Awesome</option>
</select>
<span id="serialString2">serialize that star rating!</span>
//Turn the select box into rating controls
$(".rating").rating();

//Show that we can bind on the select box
$("#serialStar2").bind("change", function(){
	$('#serialString2').text( $('#serialStar2').serialize() );
});

Setting the Value

There is one slight twist. In order to set the value programmatically, you have to set it, then trigger the change event on the select box.

<select name="myRating" class="rating" id="serialStar2">
    <option value="1">ALrighte</option>
    <option value="2">Ok</option>
    <option value="3">Getting Better</option>
    <option value="4">Pretty Good</option>
	<option value="5">Awesome</option>
</select>
<button onclick="$('#star3').val(4).change()"&gtSet to 'Pretty Good'</button&gt
//Turn the select box into rating controls
$(".rating").rating();

//Set the value to 4, then trigger change to update the rating.
$('#star3').val(4).change();

Bugfixes

  • IE Loading Problems
  • IE CSS Hover Over shows the wrong image

Todo

  • Allow disabling of the control
  • Allow global settings
  • Way to set the value without firing the change event
  • If no selected attribute is present, start with all stars blank
Share

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

76 Comments »

 
  • Mav says:

    I’ve been trying unsuccesfully to get a star rating to work in a FancyBox pop-up that loads an embedded video with a star rating via ajax. So far no luck since all seem to break on dynamically added code. I found this via http://wiki.jqueryui.com/StarRating so I thought this one might do the trick. Haven’t gotten that far yet, but I do have some thoughts:

    The thing with a select box with options is that by default the first item is always selected, which means the first star is always full upon loading. Perhaps it’s possible to put something in the options that by default none are filled? That’s my preference, I guess others might want to fill it to what’s currently the votes average.

    I also can’t seem to disable the cancel button, I noticed it’s in the options like this:
    $.fn.rating = function(options)
    {
    var settings =
    {
    showCancel: true,
    cancelValue: null,
    };

    I’m more of a PHP guy, javascript is like chinese to me so I have no idea how to set these values on $(document).ready because they’re inside the settings var. Also, imho it seems unnecessary to have settings inside options? I mean this seems more logical:
    //in custom script on $(document).ready
    $.fn.rating.options = { showCancel: false };

    //in jquery.ratings.js
    $.fn.rating.options = {
    showCancel: true,
    cancelValue: null,
    //etc...
    That’s how one of the many other ratings scripts I’ve tried did it.

  • If you can give me more information as to your problem I will try and help. An example would be best. I did just fix some IE 8 issues, so if your problem was in IE 8 redownload the file and try the new version.

    As for disabling the cancel button, all you need to do is this:

    $(document).ready(function(){
        //This is where you can turn on or off the cancel button
        $(".rating").rating({showCancel: false});
    });
    

    Passing options when you create the controls is a jQuery standard practice. In the source the var settings are the default settings that you can override by passing the option when you create the control.

    I will add the option to start with all the stars blank soon.
    Thanks for your comment!

  • Mav says:

    I’d show our testpage but since were testing on the live server because of the videos/database I’d rather not link to it here. But I got it to work in the ajax popup using .live instead of .bind like this:
    $("#serialStar2").live("change", function(){
    $('#serialString2').text( $('#serialStar2').serialize() );
    });

    So pretty much everything works now except for the first star being filled by default. IE8 did throw an error, I’ll be sure to get the updated script. And thanks for your work on this! I hope this will eventually be included into jquery UI since we’re already using parts of that already.

    About the settings thing (I guess that should be called defaults indeed :) , I meant for a way to set those options one time, not for every creation. I figured since the options code looks so much like another plugin where setting the defaults once was possible, it should be possible with this plugin too? The popup we’re using has a “callbackOnShow” that runs the $(“.rating”).rating({showCancel: false}); line, I’m assuming less code in there and more set as defaults the better. Might not make much of a difference though, but that’s why I was asking. :)

    Is there a better way of getting the two needed variables (select name & vote#)other than serializing it? Because that gives me something like: “video_003=4″ which I’ll have to split up again before I can work with the two values. Seems like the serializing is for testing/showing purposes. Sorry to ask here, I’m guessing it’s probably something very simple but I couldn’t figure that one out. JS is so not my thing, the whole PHP back-end stuff will be peanuts.

  • I understand now! Being able to globally change the settings/defaults is a good idea, I’ll add it to my TODO list.

    I just updated the control this morning which turns off all stars unless your select box has a “selected” attribute. I think this is what you wanted.

    If the jQuery serialize isn’t quite doing it for you, you can try my serializeForm plugin You use it on a containing element and it turns all of the input elements (including the rating control) into a JSON object that can be passed back to the server with $.post(url, JSON, callBack) I created the plugin for my ASP.NET work.

    In one of my production environments I put the rating into a ASP.NET control and this is the JS I use. I thought it might help with your situation. I use .bind() but .live() is great too.

    $(".rating")
    	.rating({"showCancel": false})
    	.bind("change", function(){
    		//Post the value back with ajax
    		$.post("< %= Request.Url.LocalPath %>?ajax_control=true&action=click",
    				{"tag_name":"< %= this.TagName %>", value: $("#< %= this.ID %>").val()},
    				function(xml){
    					//User Click complete, show the average
    					$("#< %= this.ID %>_avg").html(xml);
    				}
    		);
    	});
    
  • Mav says:

    Yes, exactly what I wanted. It now works with all stars off, and I like that it’s using the selected attribute if you do want to show any stars filled. In Chrome, Firefox and Opera it all works, but I tried it in msIE and it shows the first star filled. (I’m using IE7 though, haven’t updated it in a while. So it might be working in IE8?)

  • charly says:

    hi! finally a JQuery star plugin I could get to work :) Even it worked fine with a callback to a php, posting to a DB. Excellent. Thanks it’s great!

    Two things:
    1) About IE, I have IE8 and it seems to work fine in compatibility mode; it is readonly in standard mode. IE anyway didn’t to work for me with other similar plugins..
    2) Would be nice to have a readonly ability. I’m really thinking how to go about this control when users are not logged in. Readonly might be the solution.. or else any idea may help!

  • Mav says:

    Charly: As for point 2, I’m also showing only the results to guests, and only let members actually vote. The voting part is in a popup and remembers the member’s vote if they open it again. And results are shown on the main page where voting is not possible. The way I’m thinking of showing that is just completely leave the form out of it, and use a simple list for displaying the current average. That way it’s also possible to show percentages of stars.
    I’ve tested it so far with this code, which works with the star.gif from this plugin. The CSS part:
    ul.showstars {
    position: relative;
    float:left;
    list-style: none;
    margin: 0;
    padding: 0;
    width: 80px;
    height: 16px;
    background: url('star.gif') left -32px repeat-x;
    }
    ul.showstars li {
    position: absolute;
    float: left;
    display: block;
    width: 85px;
    height: 16px;
    font-size: 1px;
    }
    ul.showstars li.curr {
    background: url('star.gif') left 0;
    }
    div.staravg {
    position: relative;
    float: left;
    left: 5px;
    }

    And the HTML part:

    90%
    To get the proper px width from a percentage in PHP it's probably something like round(90*79/100);. Or (percentage * {total width of all stars-1px} / 100), the minus 1px seems to work a little better with round() but you'll have to set it to 80px when the percentage is 100%. Hope this helps. :)

  • Mav says:

    Looks like the code-tag doesn’t work properly with html tags in the comments, so here’s the html part on pastebin.

  • cute says:

    how can I get the value?
    I want to save the value in variabel..
    I work with PHP…

    thx,,,
    sorry, my English isn’t good..

  • Jeff says:

    You can get the variable by including:

    $(‘#serialStar’).val()

    in your script and then send that to a php page either through ajax or merely using the javascript window.href function to load another page with the variable as a get or post parameter.

  • cute says:

    thanks..
    I have finished it..
    But I have another problems..
    I only want to show the rating, people can’t hover and set the rating.
    Can this js do it? And how?

  • You can now make it read only by setting the select box to disabled like so: <select disabled=”disabled”>

  • Sough says:

    Hello, first nice work.

    But i have a problem with IE8, maybe you can help me.

    I think the IE8 ignore the following:

    if( 0 !== $("#" + id + " option[selected]").size() )
    {
    //Set the Starting Value
    events.setValue( $(selectBox).val(), div, selectBox );
    } else {

    After I send my formular (with a for-loop i create the button and set selected to the one, which I have choosen before) the IE8 ignore the selected. Also if I try to set select without a loop.

    With Opera, FF and older IE Versions (6, 7) and it works without any problems.

    I hope you understand what I mean (my english isn’t very well).

    Thanks for ervery help.

  • BEO says:

    I want that users are only once able to vote. How can I supply?

    $(this).attr(‘disabled’, ‘disabled’);

    doesn’t work.

  • Los says:

    Hello! I can’t seem to get the stars selected in IE8. It works fine in FF and Chrome. View source shows that the star is selected but the stars won’t light up in IE8. Anyone else have this problem?

  • Alex says:

    Is it possible to display half a star like for instance 4.5 or 3.5 ?

  • dante says:

    The issue with IE8 can be solved by following fix:


    if( 0 !== $(“#” + id + ” option:selected“).size() )
    {

  • boggers says:

    hey why hasn’t anyone answered Mav on November 7, 2009 at 2:33 pm – this control is displaying a selected star under ie7 from the start when it shouldn’t – it works in all other browsers !?

  • dungpt says:

    sucks. you did not update your code?
    did not work with jquery 1.4.2.

  • Joerg says:

    Great work, even Ajax -> DB and different stars were a piece of cake to accomplish. Works with 1.4.2 for me, as well.

    The only things I can’t quite get to work is, to disable $(this), a.k.a. the select firing the event, on Ajax success (user can only vote once), and to give a second parameter if multiple ratings are used on one page (e.g. media = “movies” or = “pics”), Any suggestions?

  • Internet Explorer 8 is very good because it is as stable as Opera. I hate the previous versions of IE like IE6 because it hangs frequently. *

  • [...] the part missing for our little tutorial is the Star Rating plugin for jQuery. Get it at http://zensoftware.org/archives/483, and put it in your “jquery” [...]

  • [...] Before continuing (or if this doesn’t work for you), you might want to familiarize yourself with the Star Rating plugin at http://zensoftware.org/archives/483. [...]

  • Vali says:

    Hello,

    How can I close the modal dialog without make postback on page
    I try $(‘.ui-dialog’).hide(); but the overlay remain in page.

    Thanks,Vali

  • Rodomo says:

    @Los I am having the same problem in IE8 with stars being “read only” – this seems to be caused by the way that IE8 is floating the stars.

    Anyone find an easy fix to this?

  • Stephen Gray says:

    @Los, @Rodomo

    Seems this plugin ignores any preselected values, guess it’s only supposed to work for values set AFTER the script is initialised. I.E. from an AJAX call etc. You can fix this by creating an array of pre selected values before you run $(selector).rating(). You then re-apply these values afterwards;


    var values = [];
    $('.selector').each(function(i, item)
    {
    if ($(this).find('option:selected').length)
    {
    values[i] = $(this).val();
    }
    });

    $('.selector').rating();

    $(values).each(function(i, value)
    {
    $('.selector:eq('+i+')').val(value).change();
    });

    I’m doing an each because I was using multiple ratings on the same page. But you get the picture.

  • Mirco says:

    Hey.
    Great Plugin! But I have a question: it is possible to reset the stars after rating?
    If I call $(‘#rateselect’).rating() again, two star-bars are shown. I’ve tried to remove the “old” bar with $(‘#rateselect’).remove() but it doesn’t work. The thing is, that I have an AJAX rating without reload the page. So if the rating is initialized once it seems to be not possible to reset the controll to rate again.
    Do somebody have an idea?
    Thanks guys :-)

  • the best thing about IE8 is that it is quite stable than previous releases of Internet Explorer;:~

  • Paul says:

    As Alex asked already: the functionality to print only half stars would be great. is there the possibility to do this?
    Thanks for the great work, Paul

  • Hey how are you doing? I just wanted to stop by and say that it’s been a pleasure reading your blog. I have bookmarked your website so that I can come back & read more in the future as well. plz do keep up the quality writing

  • selin says:

    Hi. I have a problem. I used first example of rating. But in my site also display the combobox of selection. I only want to see the star rating. Please give me an answer

  • Jako says:

    A small enhancement to get things working the same with and without javascript:

    Without javascript there has to be an empty option as first element. Otherwise the select will have the value of the first voting option and it won’t be possible to make no vote.

    To get no star for this empty option you have to extend the createStar function by surrounding it by if (elm.value) { … }

    For those selects .rating has to be invoked with startValue: ” (and cancelValue: ” if showCancel not false)

    Regards
    Jako

  • ~*- I am very thankful to this topic because it really gives great information ,.:

  • Mihai P says:

    This code is useful. I just manage to save the vote into file (can be done to save to DB). I put this
    //Show that we can bind on the select box
    $(“#serialStar3″).bind(“change”, function(){
    $.post(“salvare_vot.php”, { nota_vot: $(“#serialStar3″).val(), time: “2pm” } );
    });

    And in the salvare_vot.php I retrieve the $_POST["nota_vot"] and save it to a file or DB.

    The Problem:

    this plugin works with jQuery 1.3.2. On this page: http://www.mcdc.ro/googlemaps/gts/ I tried to implement the rating star. The slider uses already jQuery 1.4.2 and works well on jQuery 1.5. When I am using both plugins, rating star doesn’t show the stars, but the select element.
    How can I change the rating star script to work at least with jquery 1.4.2 ?

  • Michael says:

    I think I have found the rating plugin not working correctly with jquey 1.5.

    My problem is that the cancel button does cannot reset to zero stars.

    I think the underlying problem is that $(‘select’).val(null) is behaving differently in the new version of jquery. val(null) always selects the first option-element.

    Any hints for a workaround?

  • NaZaf says:

    Hi,
    How can I use this plugin just to create a readonly rating stars?
    I need to do the following exatcly, I need a “select” element with option 1 as 1-star image, option 2 as 2-stars image, and so on. Is that possible?

  • Taher says:

    Hi,

    Nice pluging. But i m having problem with IE 8. I have a page where i load the ratings from database and show the stars pre selected. Works fine in FF, Chrome etc but does not work in IE8. Works fine in compatibility mode. In IE8 can’t make the stars pre selected. Even your example (the first one which has 3 starts selected) does not display selected starts in my IE8..

    Please help

    -Taher
    Taher´s last blog ..WebService Studio – To the rescueMy ComLuv Profile

  • NaZaf says:

    @Taher
    I have the same problem. I think the problem is with jQuery attribute selector which is not working in IE 8

    $("#selectId option[selected]")

    This code does not work in IE8, that's why the plugin cannot preselect the stars!

  • Taher says:

    @Nazaf : Any solutions you got ? I badly need it, don’t want to make a rating control by myself :(

    -Taher
    Taher´s last blog ..Using the IN Clause in Stored procedure – SQL ServerMy ComLuv Profile

  • NaZaf says:

    @Taher
    Yes, I think I solved it. but it is not perfect because if there is no selected option, the first option is implicitly selected in IE8. Anyway, i that is OK to you then do the following:

    open “jquery.rating.js” in notepad or whatever and replace “[selected]” with “:selected”. I am using version 1.5 by the way

    Let me know if it does not work!

  • Taher says:

    @Nazaf:

    I did some other work around…

    I replaced the below code

    “//Is there an element with the select option set?
    if( 0 !== $(“#” + id + ” option[selected]“).size() )”

    With my custom code (Non JQuery Code)


    var selectOptions = document.getElementById(id).getElementsByTagName("option");
    var selectOptionCount = 0;
    for (var i = 0; i 0) {
    //Set the Starting Value
    events.setValue($(selectBox).val(), div, selectBox);
    }

    Now.. for my selected starts.. instead of giving selected=”selected”.. I am giving class = “selected”
    Because if no option is selected, IE was by default taking the first option as selected.

    Hope this helps !
    Taher´s last blog ..MVC for DummiesMy ComLuv Profile

  • Taher says:

    Sorry the code did not come properly in the previous post…

    Below is the code

    —————————————-

    var selectOptions = document.getElementById(id).getElementsByTagName(“option”);
    var selectOptionCount = 0;
    for (var i = 0; i 0) {
    //Set the Starting Value
    events.setValue($(selectBox).val(), div, selectBox);
    }

  • Pierre says:

    Thank you for this nice Widget!

  • zeroone says:

    Sorry! my E is poor!

    How to bind the event: mouserover , I want to show the text inner a when i mouseover the rating

  • LUCIANO says:

    Cinta tanpa kepercayaan akan hangus terbakar oleh api cemburu. – http://t.co/GuwBUNHN

  • It is perfect time to make some plans for the longer term and it’s time to be happy. I have learn this put up and if I may I wish to counsel you some interesting things or suggestions. Perhaps you can write next articles referring to this article. I wish to learn more things approximately it!

  • computer telephony integration software…

    [...]Star Rating Plugin for jQuery | Write or Program[...]…

  • dive master says:

    dive master…

    [...]Star Rating Plugin for jQuery | Write or Program[...]…

  • vacaciones says:

    vacaciones…

    [...]Star Rating Plugin for jQuery | Write or Program[...]…

 

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

CommentLuv Enabled