Mohamad
Mohamad

Reputation: 35349

Document.ready function causing a form to submit 10 times

I'm using jQuery Stars Rating plugin ( http://www.fyneworks.com/jquery/star-rating/ ).

I'm having difficulty displaying an existing rating using the plugin's API. Everything works unless there is an existing rating in the database. If there is one, the following block of code will execute, and a 10 new ratings (that's as many inputs I have in my form) get sent to the back-end rating function.

<cfif aRating.recordCount>
    <script type="text/javascript"> 
        $(document).ready(function() {
            $('input').rating('select','#aRating.rating#');
        });
    </script>
</cfif>

This ajax call should ONLY execute when a user clicks on the stars

// Ajax submit rating
$('.star').rating({
    callback: function(value, link){
        $.ajax({
            type: "POST",
            url: "#URLFor(controller="membros", action="rateGame", key=gameProfile.id)#",
            data: "rating="+value,
            dataType: "json",
            success: function(response) {
            }
        });
    }
});

The form

<form class="rate-game">
    <input type="radio" name="star" class="star {split:2}" value="0.5">
    <input type="radio" name="star" class="star {split:2}" value="1">
    ... until 10
</form>

Any ideas what's causing the function to fire 10 times? If I remove the document.ready function, nothing happens, and the existing rating is not selected.

Upvotes: 1

Views: 781

Answers (1)

Pointy
Pointy

Reputation: 413956

The problem is that, well, the plugin API is weird. When you call:

$('input').rating('select', xxx);

it does the same thing for each input element. One of the things it does is invoke your callback function! You can make it not do that by passing in an extra argument of "false" there:

$('input').rating('select', xxx, false);

The following is incorrect and left here as a historical tidbit:

Your jQuery selector:

$(".star")

selects every one of your radio buttons and runs the code for each one. If you mean to do it only for the currently-selected button, try

$(".star:checked").rating({ ... })

Upvotes: 2

Related Questions