Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting the value from HTML into javascript

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading