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

101
Visualizações
The value of my newly appended button returns undefined or nothing at all

I am trying to obtain the value of a newly appended button, however it always logs undefined or nothing. I have tried many methods, such as .val(), .textContent, and .value, as I have found those on here.

Here is my code.

}).done(function (response) {
  var lat = response.data[0].latitude;
  var long = response.data[0].longitude;

  //Appends new button based on recent search
  searchHistory.append(`<button class="col-12 btn border-info m-1" id="prevSearch">${textInput.val().toLowerCase().split(' ').map((s) => s.charAt(0).toUpperCase() + s.substring(1)).join(' ')}</button>`);

  var previousSearch = $("#prevSearch");

  previousSearch.on('click', () => {
    console.log($(this).val();

    console.log(document.getElementById("prevSearch").textContent); 
  })
})

The first log under the click function returns undefined, while the second one returns the actual content. However it only works with the first button that is appended when I try a console.log("test").

So in summary, I have 2 Issues, I can't get the value of the button and only the first button works when tested with a simple console log.

Any help would be greatly appreciated.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You're getting the button by ID. If you're adding multiple elements with the same ID, that won't work since IDs must be unique within the document.

As for your button value, I'd say just use $(this).text(). Browser support for the element content as HTMLButtonElement.value has a patchy history.

I'd just use the following

const button = $("<button>", {
  type: "button",
  "class": "prevSearch col-12 btn border-info m-1",
  text: textInput.val().replace(/(^| )[a-z]/g, c => c.toUpperCase())
}).appendTo(searchHistory)

button.on("click", function() {
  console.log($(this).text())
})

You could also move the event handling to a delegated handler outside of this code that can handle all current and future button clicks

searchHistory.on("click", ".prevSearch", function() {
  console.log($(this).text())
})
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