Search code examples
javascripthtmljavascript-objects

how to pass dynamic params to html onclick written in javascript?


function populateProductsToHomepage() {
  let divToPopulate = '';
  const {products} = apiResponse;
  products.forEach((product, i) => {
    if (product.type === 'featured') {
      const stringifiedProduct = JSON.stringify(product);
      divToPopulate += `<div
      class="col-md-6 col-lg-4 p-1 best"
      id="${product._id}"
      onclick="storeIdInLocalStorage(this)"
    >
      <a href="singleproduct.html" class="text-decoration-none text-dark">
        <div class="collection-img">
          <img src="${product.images[0]}" class="" width="100%" alt="" />
        </div>
        <div class="text-center">
          <p class="fw-bold text-capitalize my-1 text-start">${product.name}</p>
          <p class="fw-normal text-end">PKR ${product.price}</p>
          <p class="fw-light text-start">${product.shortDescription}</p>
          <a class="btn btn-primary mt-3" data-toggle="modal" data-target="#exampleModalCenter" onclick="addToCart(${stringifiedProduct})">Add to Cart</a>
        </div>
      </a>
    </div>`;
    }
  });
  document.getElementById('homepageProductsContainer').innerHTML =
    divToPopulate;
}

issue is with passing object in param on onclick function getting unexpected end of input I tried a lot of methods but still failed


Solution

  • Example for the comment from Rory

    Add the product id as data attribute to the div, remove the onclick and add a class that we use for the click handler:

          divToPopulate += `<div
          class="col-md-6 col-lg-4 p-1 best product-click"
          data-product-id="${product._id}"
        >
    

    Now we add a click handler referencing the new class (but bound to the document, as products can be added dynamically) that fetches the id from the data attribute:

    document.addEventListener("click", function(e){
      const target = e.target.closest(".product-click");
    
      if(target){
        const productId = target.dataset.productId;
        storeIdInLocalStorage(productId);
      }
    });
    
    

    Hope this helps!