Jquery onclick button background color change

I have a rating system. See this JsFiddleLink

Five stars shaped. This is one of them:

<input type="radio" name="rGroup" value="1" id="r1"/>
<label class="radio" for="r1"></label>

      

Clicking on a star simply changes the background image and turns the star blue.

  $(".radio").click(function() {
              $(this).css("background", "url(http://mykadamtala.com/projects/ip/star-blue.png)");
        });

      

But I want to change the way it appears. If users click on the second star, the background image should change for the first and second stars, and the two become blue stars. If users click on the third star, all three stars on the left turn blue. But not the fourth and fifth.

And if users click on the fifth star, the entire star turns blue. This is because they know they have given two, three, or five stars.

Jquery has to deal with this problem as well: the user clicks on the third star and all three stars on the left turn blue, but again the user clicks on the second star (because the user might change his mind) and now it should show two blue stars instead of three.

+3


source to share


2 answers


Try this code:

$(".radio").click(function() {
    var r = $(this).attr('for');
    var input = $("#"+r);
    var input_value = input.val();

    var i;
    for(i=1;i<=5;i++) {
        $("#r"+i).next().css("background", "url(http://mykadamtala.com/projects/ip/star.png)");
    }

    var ii;
    for(ii=1;ii<=input_value;ii++) {
        var ch = "#r"+ii;
        $(ch).next().css("background", "url(http://mykadamtala.com/projects/ip/star-blue.png)");
        $(ch).css("background", "url(http://mykadamtala.com/projects/ip/star-blue.png)");
    }
});

      



when you get value = [1,2,3..]

, the loop for

will run from 1 to whatever maximum value and change the background.

and also when the button is pressed less than the start than before (Ex. pressed 5 and then pressed 3).

+3


source


Since you want to account for the possibility of selection more than once, you simply cross out the selection and then show it again.



$(".radio").click(function() {
    var $this = $(this); //Current label
    var $labels = $this.parent().children('label'); //Get all labels
    var num = $this.prev().val(); //Get index of selection

    //Remove all stars
    $labels.css("background", "url(http://mykadamtala.com/projects/ip/star.png)");

    //Set stars
    for(var i = 0; i < num; i++) { 
        $labels[i].style.background = "url(http://mykadamtala.com/projects/ip/star-blue.png)";
    }
});

      

+1


source







All Articles