views:

1171

answers:

1

I'm a newbie to jquery, but am trying to use it in my project. I'm trying to loop through all the links inside #rate_box and add a click event to them. This click event will post some data to an external php script, and then it should unbind the click events on all of the links (so people cannot rate twice in quick succession.) Then it should put the data recieved from the php script into a span tag called #status.

However my code isn't even executing the alert("Index: "+i). Am I binding it correctly?

<script type="text/javascript">
 $(document).ready(function(){
  $('#rate_box a').each(function(i) {
   $(this).click(function() {
    alert("Index: "+i);
    $.post("../includes/process/rating.php", {id: "<?php $game_id ?>", type: "game", rating: i+1},
    function(data) {
     $('#rate_box a').each(function(i) {
      $(this).unbind('click');
     }
     $('#status').html(data).fadeIn("normal");
    });
   });
  });
 });
</script>
+3  A: 

You don't need to loop through each link binding a handler individually, you can just do this:

// bind click handler to all <a> tags inside #rate_box
$('#rate_box a').click(function() {

});

Same goes for unbinding:

$('#rate_box a').unbind('click');

As far as your code, it probably isn't executing because you have not closed the inner each when you are unbinding the element tags, so it is invalid javascript:

$('#rate_box a').each(function(i) {
    $(this).unbind('click');
} // <- missing closing ");"

You should really use a tool like Firebug or Firebug Lite to debug your javascript, although something like the above should just give you a Javascript error in most browsers.

EDIT If you want to find the index of the current link when it is clicked upon, you do this:

var links = $('#rate_box a');
$(links).click(function() {
    // this is to stop successive clicks on ratings,
    // although the server should still validate to make
    // sure only one rating is sent per game
    if($(this).hasClass('inactive_for_click')) return false;
    $(links).addClass('inactive_for_click');
    // get the index of the link relative to the rest, add 1
    var index = $(links).index(this) + 1;
    $.post("../includes/process/rating.php", {
        id: "<?php $game_id ?>",
        type: "game",
        rating: index
    }, function(data) {
        $('#status').html(data).fadeIn("normal");
        // unbind links to disable further voting
        $(links).unbind('click'); 
    });
});
Paolo Bergantino
I need to know the index of each individual thing being binded (it will be 0-4) because the Ajax will post that data to an external script (it is a 5-star rating system)
Tom
Updated my code to show how to accomplish this.
Paolo Bergantino