0

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?

4
  • What elements are .one-value and .another-value? Commented Jun 18, 2013 at 9:44
  • html will return any html tag, I suggest to use text() instead, plus add a parseInt Commented Jun 18, 2013 at 9:45
  • No, you don't have to use variables. Please post more of your code and the HTML and create a jsfiddle demo. Your code works fine for me: jsfiddle.net/qt8ve. Commented Jun 18, 2013 at 9:46
  • it's working fine to me. Here's my experiment jsfiddle.net/vonDy2791/btGmU Commented Jun 18, 2013 at 9:47

4 Answers 4

3

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:

Sign up to request clarification or add additional context in comments.

2 Comments

"These values are numbers inside a html span with the corresponding class."
@Felix: then the question was edited, I think; that wasn't there on the first reading. Also, updated to reflect the use of text() in place of val().
2

convert them into numbers

 $('.sum-value').html(
 parseInt($('span.one-value').text()) * parseInt(($('span.another-value').text()))
);

FIDDLE.

Comments

0

Try this:

$('.sum-value').text(parseInt($('.one-value').text()) * parseInt($('.another-value').text()));

Comments

0
$('.sum-value').html(function () {
    var n1 = parseFloat($.trim($('.one-value').text()));
    var n2 = parseFloat($.trim($('.another-value').text()));
    return n1 * n2;
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.