Noah Telussa
Noah Telussa

Reputation: 151

jQuery star rating plugin variable doesnt return correctly

I'm making a rating system to rate a movie using 5 stars. I use the jQuery bar plugin for this (jQuery bar plugin).

Someone can vote from 1 to 5. The data is stored in the database. After someone votes the stars will be disabled and show the amount of stars the user rated.

With the initialRating value of the plugin it will define how many stars are 'selected'. So if this variable is 4, 4 stars will be colored.

When I hard code for example initialRating: 4 it works. Although when I use initialRating: currentRating (the voted amount of stars) it won't return the right amount and it will just show 1 star. When I console.log currentRating it will return 4.

So how does it come that hardcoding 4 works, instead of currentRating (with the value of 4) which doesn't work.

Code

$(function () {

    currentRating = $(".rating").val(); //Getting the value that someone vote previously
    console.log(currentRating); // Displays 4

    $('#rating').barrating('show', {
        theme: 'fontawesome-stars',
        showSelectedRating: true,
        initialRating: currentRating,
        onSelect: function (value, text) {
            movieTitle = $('.movie-name'). text(),
               tmdb_id = $(".imdb_id").val(),
                _token = $(".csrf_field").val();

            $.ajax({
                headers: {
                    'X-CSRF-TOKEN': _token
                },
                method: "POST",
                url: "/movies/" + tmdb_id + "/rate",
                data: {
                    title: movieTitle,
                    tmdb_id: tmdb_id,
                    rating: value
                },
                success: function (result) {
                    $("#div1").html(result);
                }
            });
        } 
    });
});

enter image description here

Upvotes: 4

Views: 200

Answers (1)

Leguam
Leguam

Reputation: 1212

The variable currentRating is a string whereas the plug-in is expecting a integer.

Converting the string into an integer using parseInt() will solve the problem.

Code

currentRating = parseInt(currentRating);

Upvotes: 1

Related Questions