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

Buttons

Hello,

Now I've learned in here for almost 3 weeks now, and now I want to make a small project to put everything together.

I'm using codepen to make a simple calculator in html/css/JS - but now I have a problem with the JS because I can't seem to remember how I can add content (numbers) to my input-field when I press a button :-/ I've been looking everywhere but I can't find the video that teach you about this topic.

I hope someone in here can help me figure out this so I can continue my project.

Thank you very much :-)

2 Answers

Steven Parker
Steven Parker
243,318 Points

You didn't say where the content to be added was coming from, but assuming it's just literal values in the code (and by "add content to" you mean "append"), here's a simple example:

code.html
<input id="test" type="text" />
<button onclick="addit()">Add Numbers</button>
script.js
function addit() {
  document.getElementById("test").value += "123";
}

If you meant "add" as in "sum the numbers" you could do something like this in the function instead:

script.js
function addit() {
  document.getElementById("test").value = Number(document.getElementById("test").value) + 123;
}

Right now it's just a div with an input-field (where the numbers are shown) and a bunch of numbers (0-9 +, -, *, /). When I press a button I want it's value to shown in the input-field etc..

With the code you just made I need to make a indiviual code for every button?

right now the html looks like this:

<div id="calc">
  <input type="text" id="value" value="" disabled>
    <button type="button" value="7">7</button>
    <button type="button" value="8">8</button>
    <button type="button" value="9">9</button>
    <button type="button" value="+">+</button>
    <button type="button" value="4">4</button>
    <button type="button" value="5">5</button>
    <button type="button" value="6">6</button>
    <button type="button" value="-">-</button>
    <button type="button" value="1">1</button>
    <button type="button" value="2">2</button>
    <button type="button" value="3">3</button>
    <button type="button" value="*">*</button>
    <button type="button" value="0">0</button>
    <button type="button" value="=">=</button>
    <button type="reset">C</button>
    <button type="button" value="/">/</button>
</div>