Harry Treddery
Harry Treddery

Reputation: 21

How to get value of clicked button in calculator

I have multiple buttons containing different values

<button data-action="digit" class="button" id="1">1</button>
<button data-action="digit" class="button" id="2">2</button>
<button data-action="digit" class="button" id="3">3</button> 

And I want to get these buttons to display on my calculator using this in javascript:

function digit_pressed(digit) {
    

    console.log("digit pressed: " + digit);
}

But I am unsure what to add to my function. Any help would be greatly appreciated :)

Upvotes: 2

Views: 2166

Answers (1)

Simone Rossaini
Simone Rossaini

Reputation: 8162

You can use querySelectorAll for select all button then use addEventListener for add click event and last step use textContent for number of digit and call function.

document.querySelectorAll('button').forEach(el =>{
  el.addEventListener('click', () =>{
    digit_pressed(el.textContent);
  });
});
function digit_pressed(digit) {
  console.log("digit pressed: " + digit);
}
<button data-action="digit" class="button" id="1">1</button>
<button data-action="digit" class="button" id="2">2</button>
<button data-action="digit" class="button" id="3">3</button>

Reference:

Upvotes: 2

Related Questions