简体   繁体   中英

jquery onclick radio button background change

I have a star rating system. Please see this JsFiddleLink

There are five stars in the form. This is one of them:

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

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

  $(".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 clicks on the second star, the background image should change for the first and second star and they two become blue stars. If users clicks on the third star, all three star from left become blue one. But not the the fourth and fifth one.

And if users clicks on the fifth star all star becomes blue. It is because to let them know that they have given two, three or five star rating.

Jquery should also handle this issue: User clicks on the third star and all three stars from left becomes blue, but again user clicks on the second star(because user can change his mind) and now it should show two blue stars not three.

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)");
    }
});

as you get the value = [1,2,3..] the for loop will run from 1 to whatever maximum value there is and change the background.

and also when clicked less start than before (Ex. clicked 5 then after clicked 3) works.

Since you want to account for picking more than once, you simply blank out the selection, then display 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)";
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM