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

js is showing [object HTMLButtonElement] onclick?

When button clicked JS is showing [object HTMLButtonElement] instead of original value.

I want that whenever a button is clicked the value of button is showed.
like when button having value 3 is pressed it will show 3 and not [object HTMLButtonElement]

this is my html file

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

<div class="col-3">
    <button onclick="val(this)" id="n1" value="1" type="button" class="btn btn-outline-primary "
        style="width:100%" value="1">1</button>
</div>
<div class="col-3">
    <button onclick="val(this)" id="n1" value="2" type="button" class="btn btn-outline-primary "
        style="width:100%" value="2">2</button>
</div>

This is my script.js

function val(num) {
  let n = num;
  document.getElementById("ta").innerHTML = n;
}

enter image description here

>Solution :

Using onClick directly on Elements is not really ideal, try using addEventListener.

Another advantage of addEventListener you can create a delegated event handler, so if you have lots of buttons doing the same thing you can attach one handler to a parent element and all the buttons can be handled.

Buttons don’t store values like INPUT, but if you want to associate data with buttons try using the data- attribute. eg.. data-val="1", you can then access this using the dataset property.

Below is a simple example of using addEventListener as a delegated event handler, plus using data- attributes on buttons.

Update: Buttons do have the value attribute, so you could still do
e.target.value too, but I’ll leave the data- attribute as it’s
pretty handy anyway.. 🙂

const d = document.querySelector('div');

document.body.addEventListener('click', e => {
  const val = e.target.dataset.val;
  if (val) d.innerText = val;
});
div {
  border: 1px solid black;
  margin-top: 10px;
  padding: 20px;
  font-size: 30pt;
  font-family: arial;
}
<button data-val="1">1</button>
<button data-val="2">2</button>
<button data-val="3">3</button>
<button data-val="4">4</button>

<div>
  Click button above.
</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