user9375528
user9375528

Reputation:

Math script not working how I want it to work

I have this script that is design to get the values in the targeted p tags which consist of numbers which I end up using as a addition situation the problem is the

answer is suppose to be 3 not 12 the script is treating the plus symbol as a concatenation situation so how can I make the script do addition in that situation with the the variable one and two?

Here is my code

var one= document.querySelector('#oneEx').innerHTML;
var two= document.querySelector('#twoEx').innerHTML;

var total= one+two;

document.write(total);
.mathDesign{
  display: inline-block;
}
<p id='oneEx' class='mathDesign'>1</p>
<p class='mathDesign'>+</p>
<p id='twoEx' class='mathDesign'>2</p>
<p class='mathDesign'>=</p>

Upvotes: 0

Views: 110

Answers (2)

Akhil Aravind
Akhil Aravind

Reputation: 6130

You need to convert it into number before adding. innerHTML always returns a string. so in order to add them, first convert to number. parseInt() for integer and parseFloat() for floating point, or just Number()

var one= document.querySelector('#oneEx').innerHTML;
var two= document.querySelector('#twoEx').innerHTML;

var total= Number(one) + Number(two);

document.write(total);
.mathDesign{
  display: inline-block;
}
<p id='oneEx' class='mathDesign'>1</p>
<p class='mathDesign'>+</p>
<p id='twoEx' class='mathDesign'>2</p>
<p class='mathDesign'>=</p>

Upvotes: 0

Priyal Pithadiya
Priyal Pithadiya

Reputation: 889

@fsofb, when you get innerHTML then var type is HTML content. so basically your "+" here join two string value not the integer. so convert that string to integer and try.

Convert your

 var total= one+two;

With

 var total= parseInt(one)+parseInt(two);

and it works!!

Upvotes: 1

Related Questions