Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript and the DOM (Retiring) Making Changes to the DOM Getting and Setting Text with textContent and innerHTML

Christopher Phillips
Christopher Phillips
10,061 Points

Trying to add two input boxes - but it is concatenating. Where is my error?

Hi, I am trying to expand on this video but it's not resulting in what I expect.

I have the basic HTML. Two input boxes plus a button. The intended functionality is that I add a digit to the first and second box, and h1 changes to "The sum of the numbers is XX" If I use 1 and 2 it's suppose to be The sum of the numbers is 3 however my code is concatenating it and instead reads ...12. But I've used my parentheses correctly in the sense that it should evaluate 1+2 before adding it to my string.

Where is my error?

<!DOCTYPE html>
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>

</head>

<body>
<h1>This is heading 1</h1>
<input type="text" value="" class="firstNumber">
<input type="text" value="" class="secondNumber">
<button class="changeInput">Change Input</button>

<h2>This is heading 2</h2>

<p>This is a paragraph</p>


<script src="htmlTesting.js"></script>
</body>

</html>

And the JS:

const headingOne = document.querySelector('h1');
const firstNumber = document.querySelector('.firstNumber');
const secondNumber = document.querySelector('.secondNumber');
const button = document.querySelector('button');

button.addEventListener('click', () => {
  headingOne.textContent = "The sum of the numbers is " + (firstNumber.value + secondNumber.value);
})

1 Answer

Stephan Olsen
Stephan Olsen
6,650 Points

When you get the value from the input fields, they are actually of the type string. This is the reason they are being concatenated when you add them together. In order to get the sum, you first need to convert them to a number or an int. You can use

parseInt(string);
Number(string);
Amrit Pandey
Amrit Pandey
17,595 Points

Correct,

The input fields accept Strings you need to parse it to int.

button.addEventListener('click', () => {
  headingOne.textContent = "The sum of the numbers is " + (parseInt(firstNumber.value)+ parseInt(secondNumber.value));
});