The bootstrap-rating is a simple and easy to use jQuery plugin for creating rating controls. We used it in Stackweek’s feedback form.

However, the bootstrap-rating is missing functionality that we found important for usability.

Once user clicks on a star and gives some rating, there is no way to undo it. We thought it would make sense to reset the rating control if user clicks the star that was previously selected.

Let’s see how we can customize the functionality and add “unselect” action.

For creating rating control we just need to call the rating() function on the input element:

$('input').rating();

This will create the rating control with default design and functionality. The function rating() takes an optional argument, which can be used to customize the control:

$('input').rating({
  extendSymbol: function (rate) {
      // custom code called at creation
  }
});

Every time a rating symbol is created the extendSymbol callback is called. The callback’s context is the rating symbol DOM element and receives the rate as parameter. You can bind event handlers, add attributes, add classes, or anything you need to customize it.

$('.input').rating({
extendSymbol: function (rate) {
  $(this).on('click', function() {
    var inputEl = $(this).parent().next();
    var newValue = rate;
    if ( rate == inputEl.data('selected-value')) {
      newValue = 0;
      inputEl.rating('rate', newValue);
    }
    inputEl.data('selected-value', newValue);
  });
}
});

The code is very simple. We’re using the selected-value attribute to store the selected rate value. When user clicks on a star we compare it with previously selected value. If they are the same we reset the rate value.