简体   繁体   中英

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();

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!

You need to update from

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

to

 var num = document.getElementById('myButton').innerHTML;

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;
}

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM