Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

237
Views
How to push html button value attribute into the array on js?

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);
}```
  
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

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 class="buttons">
  <button value="btn1">BTN1</button>
  <button value="btn2">BTN2</button>
</div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!