Reputation: 1579
Im trying to perform simple calculations using jQuery but I'm getting NaN as result.
Here is my javascript:
$(document).on('click','.button-group button:not(.done)', function(e){
e.preventDefault();
$(this).addClass('active');
var votevalue = $(this).data('votevalue');
var image_id = $('.mainimage').data('image_id');
var votes = $('.mainimage').data('numvotes');
var totalscore = $('.mainimage').data('totalscore');
$.ajax({
type: 'POST',
url: '?a=vote',
data: {
"votevalue" : votevalue,
"image_id" : image_id
},
success: function(){
var votes = parseInt(votes);
votes++;
var average = ((parseInt(totalscore) + parseInt(votevalue)) / votes);
$('#vote-incremenet').html(votes);
$('#display-average').html(average);
$('#display-average').show();
$('.button-group button').addClass('done');
}
}); // end ajax
}); // end click
What am I doing wrong?
Upvotes: 2
Views: 3181
Reputation: 46728
When you use parseInt, be sure to pass (parseInt(str), radix)
to prevent an automatic conversion to some other base.
If the input string begins with "0x" or "0X", radix is 16 (hexadecimal).
If the input string begins with "0", radix is eight (octal). This feature is non-standard, and some implementations deliberately do not support it (instead using the radix 10).
For this reason always specify a radix when using parseInt.
(MDN)
In your case, parseInt(varname, 10);
If the issue persists, it is likely you are passing an incorrect value to one of the variables you are using for calculation.
EDIT:
var votes = parseInt(votes);
inside the call-back makes it a local variable. Hence,it has lost the value it was given outside. Do not redeclare it within the callback.
Upvotes: 3