How can i push the value of my button into the array in JS? I already have a code but it keeps pushing the btn1 value but not the btn2
<button id="btn1" value="btn1" onclick="clicked()">BTN1</button>
<button id="btn2" value="btn2" onclick="clicked()">BTN2</button
JS
function clicked(){
var btn = document.getElementById("btn1");
var newBtn = btn.value;
arraySelected.push(newBtn);
console.log(arraySelected);
}```
CodePudding user response:
Take the value of the target of the event and push it into the array
const arraySelected = [];
function clicked(e) {
const newBtn = e.target.value;
arraySelected.push(newBtn);
console.log(arraySelected);
}
<button id="btn1" value="btn1" onclick="clicked(event)">BTN1</button>
<button id="btn2" value="btn2" onclick="clicked(event)">BTN2</button>
CodePudding user response:
It's because you're always selecting the value of the first button.
getElementById('btn1')
Generally, with more modern JS, instead of inline code in the HTML, we use addEventListener
. You can use querySelectorAll
to get the buttons and attach listeners to them as I've done in this example...
const buttons = document.querySelectorAll('button');
buttons.forEach(button => {
button.addEventListener('click', handleClick, false);
});
const arraySelected = [];
function handleClick(e) {
const { value } = e.target;
arraySelected.push(value);
console.log(arraySelected);
}
<button value="btn1">BTN1</button>
<button value="btn2">BTN2</button>
...or you can use event delegation on a parent component so you're only using one listener to catch the click events from child elements as they "bubble up" the DOM.
const buttons = document.querySelector('.buttons');
buttons.addEventListener('click', handleClick, false);
const arraySelected = [];
function handleClick(e) {
if (e.target.matches('button')) {
const { value } = e.target;
arraySelected.push(value);
console.log(arraySelected);
}
}
<div >
<button value="btn1">BTN1</button>
<button value="btn2">BTN2</button>
</div>