0

I am trying to create a thumbs up/down rating demo http://jsfiddle.net/HfNL9/1/

var ups = 0;

$('.rating .voteup').on('click', function () {
    var currentId = $(this).attr('href');
    ups = ups + 1;
    $(currentId + ' > .up').html(ups);

    return false;
});

var downs = 0;

$('.rating .votedown').on('click', function () {
    var currentId = $(this).attr('href');
    downs = downs + 1;
    $(currentId + ' > .down').html(downs);

    return false;
});

However it keeps the count for elements with different ids, please see the fiddle (click both thumbs ups or thumbs down to see what I mean). How do I resolve this?

sdvnksv
  • 9,350
  • 18
  • 56
  • 108
  • You're using a unique variable "ups" for all votes so of course it keeps the same value for all votes. You should use .data() instead so that each vote has it's own count, or .attr('data-count', /**/ ). – Virus721 Mar 21 '14 at 10:29
  • You might be posting the data back to server, using ajax. According to me you need not worry about it. The last count will be received from server, so you won't need to worry about the unique variable problem. – Bhavik Mar 21 '14 at 10:32

1 Answers1

1

Try this

$('.rating .voteup').on('click', function () {
    var up = $(this).closest('div').find('.up');
    up.text(parseInt(up.text()) + 1);
    return false;
});
$('.rating .votedown').on('click', function () {
    var down = $(this).closest('div').find('.down');
    down.text(parseInt(down.text()) + 1);
    return false;
});

DEMO

Anton
  • 32,245
  • 5
  • 44
  • 54