Search code examples
javascriptjqueryundefined

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.


Solution

  • 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())
    })