Search code examples
javascriptjqueryraty

How to update raty value


I am using jquery raty plugin, there is a click event which I am using to send rating data and then return new rating from database, but I cant figure out how to update returned rating, my code:

    $('.starrating').raty({
            number:10,
            score: function() {
                  return $(this).attr('data-rating');
                 },
            click: function(score, evt) {
                var contentid = $(this).attr('id');
                $.post('/main/rating.php',{score:score, contentid:contentid },
                        function(data){
                            //alert(data+' Score = '+score);
                            $(this).data('rating',2);
                });
            }
            });

I tried with below but no success;

$(this).data('rating',2);

Thanks for any help.


Solution

  • Try $(this).raty({ score: 2 }); according to raty docs

    P.S. if you additionaly need to set data attribute you can try this: $(this).raty({ score: 2 }).attr('data-rating', 2);

    P.P.S. Little click event update for right handling multiple elements

    $('.starrating').raty({
        number:10,
        score: function() {
            return $(this).attr('data-rating');
        },
        click: function(score, evt) {
            var target = $(this),
                contentid = target.attr('id');
    
            $.post('/main/rating.php',{score:score, contentid:contentid },
                function(data){
                    target
                        .raty({
                            score: data.score
                        })
                        .attr('data-rating', data.score);
                });
            }
        });