3

I'm working on star ratings. I reused code from Olga on Codepen. And I want to display dynamically the rate that the user selected like this : "You gave this product : 3/5".

I'm beginning in JS and jQuery so my ideas where limited ; I tried this just to test but it didn't show anything

if ($('.rate2-star5').is(':checked')) {
  alert("checked");
}
<head>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/rateYo/2.3.2/jquery.rateyo.min.css">
</head>
<div class="row">
  <fieldset class="rate">
    <input class="rate2-star5" type="radio" name="rate2" value="5" />
    <label for="rate2-star5" title="Awesome">5</label>

    <input class="rate2-star4" type="radio" name="rate2" value="4" />
    <label for="rate2-star4" title="Very good">4</label>
  </fieldset>
</div>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rateYo/2.3.2/jquery.rateyo.min.js"></script>

Here what I want the result to look like : https://i.stack.imgur.com/GEoOX.jpg

  • Hi @Nicolas, perhaps [this answer](https://stackoverflow.com/questions/596351/how-can-i-know-which-radio-button-is-selected-via-jquery) might help you out. – Tenzin Kunkyab May 20 '19 at 08:31

2 Answers2

1

Use the following jquery example I think it will help you.

$(document).on('change', '.rate2-star5', function() {
  var el = $(this);
  var is_checked = el.is(':checked');
  alert(is_checked);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>


<div class="row">
  <fieldset class="rate">

    <input class="rate2-star5" type="checkbox" name="rate2" value="5" />
    <label for="rate2-star5" title="Awesome">5</label>

  </fieldset>
</div>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

You can use the following snippet that is basically derived from your original jQuery code:

$("input[type='radio']").click(function() {
  if ($(this).is(':checked')) {
    alert($(this).val());
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
  <fieldset class="rate">
    <input class="rate2-star5" type="radio" name="rate2" value="5" />
    <label for="rate2-star5" title="Awesome">5</label>

    <input class="rate2-star4" type="radio" name="rate2" value="4" />
    <label for="rate2-star4" title="Very good">4</label>
  </fieldset>
</div>

Explanation:

You need to fire this code on click or change (of the value) of the radio button, then only you will see an alert.

Code_Ninja
  • 1,729
  • 1
  • 14
  • 38