varun sharma varun sharma - 6 months ago 18
Javascript Question

Set star value in form after click on star

I am implementing a star rating and am using the font awesome star in my form but I don't know how to set the star value. I have many values in this form like input and buttons. But i don't know how to the set value of a star.

https://css-tricks.com/star-ratings/

enter image description here



.rating {
unicode-bidi: bidi-override;
direction: rtl;
float:left;
}
.rating > span {
display: inline-block;
position: relative;
width: 1.1em;
}
.rating > span:hover:before,
.rating > span:hover ~ span:before {
content: "\2605";
position: absolute;
}

<form>
<div class="rating">
<span>☆</span><span>☆</span><span>☆</span><span>☆</span><span>☆</span>
</div>
</form>





I want set the value in star. After a click on the star then the star should be black.

Answer

Use some js/jQuery to apply active class for current element, replace span with label and radio inside

$(document).ready(function() {
  $('label').click(function() {
    $('label').removeClass('active');
    $(this).addClass('active');
  });
});
.rating {
  unicode-bidi: bidi-override;
  direction: rtl;
  float: left;
}
.rating > label {
  display: inline-block;
  position: relative;
  width: 1.1em;
}
.rating > label.active:before,
.rating > label.active ~ label:before,
.rating > label:hover:before,
.rating > label:hover ~ label:before {
  content: "\2605";
  position: absolute;
}
input {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <div class="rating">
    <label>☆
      <input type="radio" name="starValue" value="5" />
    </label>
    <label>☆
      <input type="radio" name="starValue" value="4" />
    </label>
    <label>☆
      <input type="radio" name="starValue" value="3" />
    </label>
    <label>☆
      <input type="radio" name="starValue" value="2" />
    </label>
    <label>☆
      <input type="radio" name="starValue" value="1" />
    </label>
  </div>
</form>

Comments