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
<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;
}
>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.valuetoo, but I’ll leave thedata-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>
