Reputation: 3615
Have little calculation:
$('.sum-value').html(
($('.one-value').html()) * ($('.another-value').html())
);
Want to calculate out of .one-value
and .another-value
. These values are numbers inside a html span with the corresponding class. So if I echo these two I get a single number.
And add the sum to .sum-value
.
Is this possible or do i have to dump .one-value
and .another-value
to a var
.
Actually it doesn't work, but I also get no error in the console.
Any suggestions?
Upvotes: 0
Views: 73
Reputation: 253307
I'd suggest:
$('.sum-value').text(function(){
var v1 = parseFloat($('.one-value').text()) || 0,
v2 = parseFloat($('.another-value').text()) || 0;
return v1 * v2;
});
We're using parseFloat()
because we want to use the number contained within the value
property, and we can't be sure it's an integer (in which case parseInt()
would be more appropriate).
We're also using || 0
to guarantee that there is a number (in case, for example, the element
is empty or holds a non-numeric value).
References:
Upvotes: 3
Reputation:
convert them into numbers
$('.sum-value').html(
parseInt($('span.one-value').text()) * parseInt(($('span.another-value').text()))
);
Upvotes: 2
Reputation: 44740
$('.sum-value').html(function () {
var n1 = parseFloat($.trim($('.one-value').text()));
var n2 = parseFloat($.trim($('.another-value').text()));
return n1 * n2;
});
Upvotes: 0
Reputation: 1684
Try this:
$('.sum-value').text(parseInt($('.one-value').text()) * parseInt($('.another-value').text()));
Upvotes: 0