Integrating CSS star rating into an HTML form

Amar H-V picture Amar H-V · Nov 14, 2011 · Viewed 105.6k times · Source

I've seen a tutorial online - http://www.htmldrive.net/items/show/402/CSS-Star-Rating-System - for making a CSS star rating system.

On the page they have this code:

<ul class="rating">
   <li><a href="#" title="1 Star">1</a></li> 
   <li><a href="#" title="2 Stars">2</a></li>
   <li><a href="#" title="3 Stars">3</a></li>
   <li><a href="#" title="4 Stars">4</a></li>
   <li><a href="#" title="5 Stars">5</a></li>
</ul>

From what I can tell, this is just a list. How would I integrate it into my form, so that the information from the star rating can be submitted to a database. My current code for the form is below:

 <p>Quality</p>
 <input type="radio" name="ratingquality" value="1"> 
 <input type="radio" name="ratingquality" value="2"> 
 <input type="radio" name="ratingquality" value="3"> 
 <input type="radio" name="ratingquality" value="4"> 
 <input type="radio" name="ratingquality" value="5"> 

Answer

Gargiya picture Gargiya · Jan 20, 2014

This is very easy to use, just copy-paste the code. You can use your own star image in background.

I have created a variable var userRating. you can use this variable to get value from stars.

Enjoy!! :)

$(document).ready(function(){
    // Check Radio-box
    $(".rating input:radio").attr("checked", false);

    $('.rating input').click(function () {
        $(".rating span").removeClass('checked');
        $(this).parent().addClass('checked');
    });

    $('input:radio').change(
      function(){
        var userRating = this.value;
        alert(userRating);
    }); 
});
.rating {
    float:left;
    width:300px;
}
.rating span { float:right; position:relative; }
.rating span input {
    position:absolute;
    top:0px;
    left:0px;
    opacity:0;
}
.rating span label {
    display:inline-block;
    width:30px;
    height:30px;
    text-align:center;
    color:#FFF;
    background:#ccc;
    font-size:30px;
    margin-right:2px;
    line-height:30px;
    border-radius:50%;
    -webkit-border-radius:50%;
}
.rating span:hover ~ span label,
.rating span:hover label,
.rating span.checked label,
.rating span.checked ~ span label {
    background:#F90;
    color:#FFF;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="rating">
    <span><input type="radio" name="rating" id="str5" value="5"><label for="str5"></label></span>
    <span><input type="radio" name="rating" id="str4" value="4"><label for="str4"></label></span>
    <span><input type="radio" name="rating" id="str3" value="3"><label for="str3"></label></span>
    <span><input type="radio" name="rating" id="str2" value="2"><label for="str2"></label></span>
    <span><input type="radio" name="rating" id="str1" value="1"><label for="str1"></label></span>
</div>