Home > Blockchain >  Getting the value from HTML into javascript
Getting the value from HTML into javascript

Time:08-04

I'm not entirely certain if what I'm trying to do may be possible. However,

<button class = "numbers" value=1>1</button>
all the way to 
<button class = "numbers" value=9>9</button>

For example, I have 1 all the way to 9, when one of these buttons were to be clicked, I want the values to be console logged. So, if I clicked the number 1 for example, it would just console log 1 as an int using the value of that specific button, without having to specify each button individually.

Thank you for helping in advance!

CodePudding user response:

Use event delegation. Add one event listener to the container of the buttons, and on click, if the target (the innermost clicked element) was a button that matches .numbers, log the value.

document.querySelector('.container').addEventListener('click', ({ target }) => {
  if (!target.matches('.numbers')) return;
  console.log(target.value);
});
<div >
  <button class = "numbers" value=1>1</button>
  <button class = "numbers" value=9>9</button>
</div>

  • Related