2

How would I add together the values pulled from two separate jQuery.html() calls? Example:

<div id="a">27</div>
<div id="b">3</div>

$(document).ready(function(){
  var a = $("#a").html();
  var b = $("#b").html();
  var c = a + b;
});

All the above does is concatenate var a and b into c (i.e. c = 273) because a & b are strings. How do I get the actual values so that I can properly add them?

4 Answers 4

4

You can do either

var a = +$("#a").html();

or

var a = parseInt($("#a").html(), 10);

both of which cast the string to an integer. For more info, see How do I convert a string into an integer in JavaScript?.

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

Comments

2

Use the parseInt() function:

$(document).ready(function(){
 var a = parseInt($("#a").html(), 10);
 var b = parseInt($("#b").html(), 10);
 var c = a + b;
});

2 Comments

Make sure to specify the base so that leading 0s don't screw things up.
Good point thanks - something I've overlooked on more than one occasion - updated my answer to reflect that.
2

You can use + in both operands

var c = +a + +b;

2 Comments

x- -y is shorter more info here
imho +a + +b is more readable than x- -y, but nonetheless good suggestion, thanks!
1

use text() instead of html().

var x = parseInt( $(el).text(), 10 );

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.