0

I am trying to get this code to calculate the total for my shopping cart project, but it just concatenates the two prices together

I tried making separate variables but it didn't work.

document.querySelector('.totalBtn').addEventListener('click', fillTotal);

function fillTotal(){

      let a = document.querySelector('.landingHempOil').innerHTML;
      let b = document.querySelector('.fishOilLanding').innerHTML;
       document.querySelector('.totalLanding').innerHTML= a + b; 
}

What happens is the total shows the two concatenated next to each other rather than adding the two prices together. how could I do this better?

Md Johirul Islam
  • 5,042
  • 4
  • 23
  • 56
Joe Powell
  • 23
  • 5
  • `innerHtml` is a string. `+` for strings concatenates them. So turn them into numbers first. –  Aug 16 '19 at 19:58
  • Possible duplicate of [Adding two numbers concatenates them instead of calculating the sum](https://stackoverflow.com/questions/14496531/adding-two-numbers-concatenates-them-instead-of-calculating-the-sum) –  Aug 16 '19 at 20:03
  • Possible duplicate of https://stackoverflow.com/questions/5961000/javascript-sign-concatenates-instead-of-giving-sum-of-variables –  Aug 16 '19 at 20:03
  • Possible duplicate of https://stackoverflow.com/questions/45840501/javascript-sign-concatenates-instead-of-giving-sum –  Aug 16 '19 at 20:03
  • is there a reason you are using innerHTML? innerText ? nodeValue? – Estradiaz Aug 16 '19 at 20:20
  • @Estradiaz Probably just following a tutorial, or it was the first thing they found online that worked. I doubt they weighed the various options and chose the optimal one. –  Aug 16 '19 at 20:48

3 Answers3

0

You need to parse a and b to numeric values like following:

document.querySelector('.totalLanding').innerHTML= parseFloat(a) + parseFloat(b); 
Md Johirul Islam
  • 5,042
  • 4
  • 23
  • 56
0

Convert the innerhtml value to integer to do the Math.

let a = document.querySelector('.landingHempOil').innerHTML;
let b = document.querySelector('.fishOilLanding').innerHTML;
document.querySelector('.totalLanding').innerHTML= parseFloat(a) + parseFloat(b); 
0

The problem is that the values are not numbers. You need to convert them into numbers before adding them. You could use Number(), or parseFloat().

function fillTotal(){

      let a = document.querySelector('.landingHempOil').innerHTML;
      let b = document.querySelector('.fishOilLanding').innerHTML;
       document.querySelector('.totalLanding').innerHTML= Number(a) + Number(b); 
}
Kavelin
  • 397
  • 1
  • 11