Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the value from an HTML button using JavaScript

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();
like image 757
sammyb123 Avatar asked Jun 07 '26 18:06

sammyb123


2 Answers

You need to update from

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

to

 var num = document.getElementById('myButton').innerHTML;
like image 57
Nikhil Aggarwal Avatar answered Jun 10 '26 08:06

Nikhil Aggarwal


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!

like image 33
Mike Donkers Avatar answered Jun 10 '26 06:06

Mike Donkers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!