Home > Net >  Problem with passing argument in onclick event while using innerHTML
Problem with passing argument in onclick event while using innerHTML

Time:09-07

I'd like to simply fetch and display data from api, to each item I want to add button where its possible to click and add item to favorite. If im trying to pass item.name as an argument to the function I got an error

index.html:1 Uncaught ReferenceError: Buzz is not defined at HTMLButtonElement.onclick (index.html:1:10)

what is strange for me if I pass item.id it works fine.

async function getAllBeers() {
  const response = await fetch("https://api.punkapi.com/v2/beers");
  const data = await response.json();
  displayAllBeers(data);
}
getAllBeers();

function displayAllBeers(data) {
  const beersContainer = document.getElementById("beersContainer");
  data.map((beer) => {
    console.log(beer.name);
    beersContainer.innerHTML  = `
      <div class='beerContainer'>
          <h3 class='name'>${beer.name}</h3>
          <img src='${beer.image_url}'></img>
          <p>${beer.description}</p>
          <button onclick='addToFav(${beer.name})'>Add to Favourite</button>
      </div>
      `;
  });
}

function addToFav(name) {
  console.log(name);
}

CodePudding user response:

You were missing to quote the '${beer.name}'

I suggest you delegate

const beersContainer = document.getElementById("beersContainer");
const displayAllBeers = data => {
  beersContainer.innerHTML = data.map((beer) => `
    <div class='beerContainer'>
      <h3 >${beer.name}</h3>
      <img src="${beer.image_url}" />
      <p>${beer.description}</p>
      <button >Add to Favourite</button>
    </div>`).join("");
};

const addToFav = name => {
  console.log(name);
};

beersContainer.addEventListener("click", function(e) {
  const tgt = e.target.closest(".add")
  if (tgt) addToFav(tgt.closest(".beerContainer").querySelector(".name").textContent)
});

async function getAllBeers() {
  const response = await fetch("https://api.punkapi.com/v2/beers");
  const data = await response.json();
  displayAllBeers(data);
}
getAllBeers();
<div id="beersContainer"></div>

CodePudding user response:

Consider what this becomes when the placeholder is replaced with data:

<button onclick='addToFav(${beer.name})'>Add to Favourite</button>

It becomes this:

<button onclick='addToFav(Buzz)'>Add to Favourite</button>

So you're trying eo execute this:

addToFav(Buzz)

Just as the error states, Buzz is not defined. Presumably you intend for this literal value to be a string:

addToFav('Buzz')

Strings have quotes around them. So your dynamic code generation logic needs to include those quotes:

<button onclick="addToFav('${beer.name}')">Add to Favourite</button>

(Note that I also replaced the quotes around the attribute value with double-quotes, which is more HTML-standard and prevents these single-quotes from interfering with the attribute value.)

  • Related