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

244
Views
¿Cómo insertar el atributo de valor del botón html en la matriz en js?

¿Cómo puedo insertar el valor de mi botón en la matriz en JS? Ya tengo un código pero sigue presionando el valor btn1 pero no el 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

Tome el valor del objetivo del evento y empújelo a la matriz

 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

Es porque siempre estás seleccionando el valor del primer botón.

 getElementById('btn1')

Generalmente, con JS más moderno, en lugar de código en línea en el HTML, usamos addEventListener . Puede usar querySelectorAll para obtener los botones y adjuntarles oyentes como lo he hecho en este ejemplo...

 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>

... o puede usar la delegación de eventos en un componente principal, por lo que solo está usando un oyente para capturar los eventos de clic de los elementos secundarios a medida que "burbujean" el 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!