3

I am making a calculator, I have already created the calculator in html and css but I am trying to move forward by making the button clicks register in the display which is what my problem is right now. I am fairly new to JavaScript so if someone could point me in the right direction on how to do it or where to find the answer I would appreciate it.

This is a the portion I am working on, trying to get button '7' to register so I can do the others.

<div class="container-fluid calc" >
 <div class="display">
  <label type="text" id="screen">0</label>

   <div class="buttons">

     <button onClick='calculate()' id='myButton'>7</button>
     <button>8</button>
     <button>9</button> 

Here is the JS I put together

function calculate(){
  var num = document.getElementById('#myButton').contentValue;
  document.getElementById('screen').innerHTML = num;
}

calculate();
1
  • getElementById('#myButton') should be getElementById('myButton'). # is used in JQuery functions Commented Jan 14, 2016 at 20:00

4 Answers 4

4

You need to update from

 var num = document.getElementById('#myButton').contentValue;

to

 var num = document.getElementById('myButton').innerHTML;
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you nikhil, that did it
4

You should use the .innerHTML function instead of the .contentValue function to do this, also, you shouldn't use a # in document.getElementById this is used in jQuery, so just the ID is enough

function calculate(){
    var num = document.getElementById('myButton').innerHTML;
    document.getElementById('screen').innerHTML = num;
}

calculate();

Hope this helps!

5 Comments

# isn't jQuery. Its a selector. You could use document.querySelector. Just to be clear. Either way +1.
@AtheistP3ace Thanks for that, honestly did not know that. Learning new stuff every day
Well then, knowledge has been spread in numerous directions this day! =]
@AtheistP3ace It seems like it has! :))
Thank you very much for your response. I tried that but its not registering on the screen, It stays blank. Is there another way of doing it?
0

Update

function calculate(){
  var num = document.getElementById('#myButton').contentValue;
  document.getElementById('screen').innerHTML = num;
}

to

function calculate(){
  var num = document.getElementById('myButton').innerText;
  document.getElementById('screen').innerText = num;
}

Comments

0

Another option is you can is data attribute like this :

<button onClick='calculate()' id='myButton' data-value="7">7</button>

and get it like this :

$("#myButton").attr("data-value");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.