Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

194
Vistas
Cómo obtener el valor del botón con JS

¿Cómo puedo obtener el valor de un botón cuando hay muchos botones múltiples creados? Actualmente en mi archivo Javascript lo tengo, así que mi historial de búsqueda hace un botón en una lista con un "valor" de la ciudad que está etiquetada.

Cuando hago clic en el botón que se hizo, me sale indefinido.

 function recentSearch(city) { var addCity = document.createElement("button"); addCity.setAttribute("value", city); addCity.textContent = city; document.getElementById("searchHistory").append(addCity); cities.push(city); localStorage.setItem("searches",JSON.stringify(cities)); }
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Si está agregando tantos botones, use la delegación de eventos . Agregue un oyente al contenedor principal, agregue sus botones y luego, en la función de oyente, verifique si el elemento en el que se hizo clic es un botón y registre su valor.

 const searchHistory = document.querySelector('#searchHistory'); // Add one listener to the container that calls `handleClick` searchHistory.addEventListener('click', handleClick, false); function handleClick(e) { // Destructure the nodeName and value from // the clicked element, and log the value if the // element is a button const { nodeName, value } = e.target; if (nodeName === 'BUTTON') { console.log(value); } } function recentSearch(city) { var addCity = document.createElement('button'); addCity.value = city; addCity.textContent = city; searchHistory.append(addCity); } const cities = ['London', 'Rome', 'New York', 'Seoul', 'Kingston']; for (const city of cities) { recentSearch(city); }
 <div id="searchHistory"></div>

about 4 years ago · Juan Pablo Isaza Denunciar

0

El siguiente código registrará el valor del botón en la consola cuando se haga clic en él.

 function recentSearch(city) { var addCity = document.createElement("button"); addCity.setAttribute("value", city); addCity.textContent = city; addCity.onclick = (e)=>{ console.log(e.target.getAttribute('value')); //or whatever other code you want to do onclick } document.getElementById("searchHistory").append(addCity); cities.push(city); localStorage.setItem("searches",JSON.stringify(cities)); }
about 4 years ago · Juan Pablo Isaza Denunciar

0

Intente usar atributos de datos . Hacen que su código sea más fácil de leer y proporcionan una excelente manera de pasar datos dentro de los elementos, y puede acceder a sus datos usando element.dataset.<attribute_name> , en este caso e.target.dataset.value (desde dentro de los botones haga clic en el oyente).

 cities = [] function recentSearch(city) { // FOR DEMO ONLY:: if (!city) city = "city " + Math.ceil(Math.random() * 1000); var addCity = document.createElement("button"); addCity.setAttribute("data-value", city); addCity.textContent = city; addCity.addEventListener('click', e => { console.log(`my city is: ${e.target.dataset.value}`); }) document.getElementById("searchHistory").append(addCity); cities.push(city); // localStorage.setItem("searches",JSON.stringify(cities)); }
 <div id='searchHistory'> </div> <button onclick='recentSearch()'>Make City</button>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda