0

I am working on a rating system and want to pull up each rating value by the jquery. For this purpose I am doing like this, but I am unable to get previous event variable value into next event.

var r1Rating;
    $(".rating-input").on("click",function(){
        //alert($(this).attr("id"));

        var r1=$(this).attr("id");
        var r1Array=r1.split("-");
        //alert(r1Array[r1Array.length-1]);
        var r1Rating=parseInt(r1Array[r1Array.length-1]).toFixed(2);
        $("#total_rating").html(r1Rating);
        var r1Rating=r1Rating;
    });

$(".rating-input1").on("click",function(){
        alert(r1Rating); //I want to get value here
});

Any help, suggestion would be appreciated. Thanks

stevenw00
  • 1,155
  • 1
  • 13
  • 22
Dinesh
  • 4,066
  • 5
  • 21
  • 35
  • you are creating `r1Rating` again in your function. remove the `var` – atmd Jul 09 '15 at 08:00
  • Do `r1Rating=parseInt(r1Array[r1Array.length-1]).toFixed(2);` (without the `var`), and remove the last line of your first function (`var r1rating = ..`) – putvande Jul 09 '15 at 08:00
  • don't declare new variable `r1Rating` inside the first click event listener (remove var keyword), and you will be able to use the one defined in the outer scope (first line) – Hacketo Jul 09 '15 at 08:00
  • See regarding variable's scope: http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript That's said, if you provide relevant HTML markup, it should be better way to do it – A. Wolff Jul 09 '15 at 08:01

2 Answers2

4

Even though you have a r1Rating in the external scope, since you are using var r1Rating in the click handler, you are creating a new locally scoped variable in the click handler. So any changes you make to the variable will be visible inside that method only and the variable in the external scope will not be updated.

var r1Rating;
$(".rating-input").on("click", function () {
    //alert($(this).attr("id"));

    var r1 = $(this).attr("id");
    var r1Array = r1.split("-");

    //should not use var here
    r1Rating = parseInt(r1Array[r1Array.length - 1]).toFixed(2);
    $("#total_rating").html(r1Rating);
});

$(".rating-input1").on("click", function () {
    alert(r1Rating); //I want to get value here
});
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
-2

The code below should be changes, since in this instance, you created a new r1Rating variable in a scope, which means that this was a different variable from the global one outside.

var r1Rating=r1Rating;

This should be changed to:

r1Rating=r1Rating;
KiiroSora09
  • 2,247
  • 18
  • 21