Search code examples
javascriptjqueryrating

Adding submit button to jquery star rating


I have a default star rating system in my smarty template. it works great for desktop users but in mobile device, I found I always tap on the wrong value. I wish I could add a button to submit my rating instead of automatically submit when user tapping on star.

        $(document).ready(function(){
            $(".one-star, .two-stars, .three-stars, .four-stars, .five-stars").click(function() {
                $("#current_rating").width($(this).html()*30);
                $.ajax({data: ({ action: 'save_rating', rating: $(this).html(), listing_id: <?php echo $id; ?>}), success: function() { window.location.href = '<?php echo $this->escape(URL); ?>'; }});
                return false;
            });
        });

            <ul class="star-rating">
                <li id="current_rating" class="current-rating" style="width:<?php echo $rating*30; ?>px;"><?php echo $rating; ?> Stars.</li>
                    <li><a href="#" title="1 star" class="one-star">1</a></li>
                    <li><a href="#" title="2 stars" class="two-stars">2</a></li>
                    <li><a href="#" title="3 stars" class="three-stars">3</a></li>
                    <li><a href="#" title="4 stars" class="four-stars">4</a></li>
                    <li><a href="#" title="5 stars" class="five-stars">5</a></li>
            </ul>

Solution

  • add this element to your html part:

    <input type=button id=submit_rating value="submit rate" />
    

    and change your jquery code to this:

    $(document).ready(function(){
            var rate=null;
            $(".one-star, .two-stars, .three-stars, .four-stars, .five-stars").click(function() {
                 rate = $(this).html();
                 $("#current_rating").width(rate*30);
            });
            $('#submit_rating').click(function(){
                    $.ajax({data: ({ action: 'save_rating', rating: rate, listing_id: <?php echo $id; ?>}), success: function() { window.location.href = '<?php echo $this->escape(URL); ?>'; }});
                    return false;
            });
        });