Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

195
Visualizações
How to get value of button with JS

How can I get the value of a button when there are many multiple buttons created? Currently on my Javascript file I have it so my search history makes a button in a list with a "value" of the city that is labeled.

When I click on the button that was made I get undefined.

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 Respostas
Responde à pergunta

0

If you're adding so many buttons use event delegation. Add one listener to the parent container, add your buttons, and then, in the listener function, check to see if the clicked element is a button, and log its value.

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 Relatório

0

The following code will log the value of the button to the console when it is clicked.

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 Relatório

0

Try using data-attributes. They make your code easier to read and provide a great way to pass along data inside of elements - and you can access their data using element.dataset.<attribute_name> - in this case e.target.dataset.value (from within the buttons click listener).

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda