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?

daveycroqet
  • 2,667
  • 7
  • 35
  • 61

4 Answers4

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?.

Community
  • 1
  • 1
Sophie Alpert
  • 139,698
  • 36
  • 220
  • 238
2

Use the parseInt() function:

$(document).ready(function(){
 var a = parseInt($("#a").html(), 10);
 var b = parseInt($("#b").html(), 10);
 var c = a + b;
});
TheOx
  • 2,208
  • 25
  • 28
2

You can use + in both operands

var c = +a + +b;
Andreas Wong
  • 59,630
  • 19
  • 106
  • 123
1

use text() instead of html().

var x = parseInt( $(el).text(), 10 );
Colin Brock
  • 21,267
  • 9
  • 46
  • 61
Larry Battle
  • 9,008
  • 4
  • 41
  • 55