0

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!

4
  • I don't think buttons really have a "value" attribute, but you could use <input type='button' value='1' />. You'll need to assign an event listener for the click event. I'd definitely look for a JS tutorial for this. Commented Aug 3, 2022 at 20:21
  • 2
    @user1599011 The <button> element has a value attribute and property. Commented Aug 3, 2022 at 20:22
  • @user1599011 Ah, is setting a value on button, not a good practice? Should I use input type instead? Commented Aug 3, 2022 at 20:36
  • I was wrong; I don't use it and didn't realize it was valid. Commented Aug 3, 2022 at 20:37

1 Answer 1

1

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 class="container">
  <button class = "numbers" value=1>1</button>
  <button class = "numbers" value=9>9</button>
</div>

Sign up to request clarification or add additional context in comments.

2 Comments

Ahh, this is what I originally thought to use event targets with a container. Thank you! :)
Ah, Event delegation and Event propagation. I'll read up on both of these again.

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.