-1

REMOVE button does not work. Even in console when i click the button nothing appears in the console. Can anyone spot the problem?

I feel like something is wrong with the classes, not sure though.

This JS for shopping cart. Its not the whole js code its just the function that included the remove button functionality.

if (document.readyState == "loading") {
  document.addEventListener("DOMContentLoaded", ready)
} else {
  ready()
}

function ready() {
  var removeCartItemButtons = document.getElementsByClassName("btn-danger")
  console.log(removeCartItemButtons)
  for (var i = 0; i < removeCartItemButtons.length; i++) {
    var button = removeCartItemButtons[i]
    button.addEventListener("click", removeCartItem)
    console.log("click")
  }

  var quantityInputs = document.getElementsByClassName("quantity__item")
  for (var i = 0; i < quantityInputs.length; i++) {
    var input = quantityInputs[i]
    input.addEventListener("change", quantityChanged)
  }

  var addToCartButtons = document.getElementsByClassName("shop-item-button")
  for (var i = 0; i < addToCartButtons.length; i++) {
    var button = addToCartButtons[i]
    button.addEventListener("click", addToCartClicked)
  }

  document.getElementsByClassName('btn-purchase')[0].addEventListener('click', purchaseClicked)
}
<table>
  <thead>
    <div class="cart-row">
      <th><span class="cart-item cart-header cart-column">ITEM</span></th>
      <th><span class="cart-price cart-header cart-column">QUANTITY</span></th>
      <th><span class="cart-quantity cart-header cart-column">PRICE</span></th>
      <th></th>
    </div>
  </thead>
  <tbody class="cart-items">
    <tr>
      <div class="cart-row">
        <td class="product__cart__item">
          <div class="product__cart__item__pic">
            <img src="img/shop/cart/cart-1.jpg" width="100" height="100">
          </div>
          <div class="product__cart__item__text">
            <h6>T-shirt Contrast Pocket</h6>
          </div>
        </td>
        <td class="quantity__item">
          <div class="quantity">
            <div class="pro-qty">
              <input type="text" value="1">
            </div>
          </div>
        </td>
        <td class="cart__price">$ 30.00</td>
        <td>
          <button type="button" class="btn btn-danger">REMOVE</button>
        </td>
      </div>
    </tr>
  </tbody>

</table>
Peter Seliger
  • 11,747
  • 3
  • 28
  • 37

3 Answers3

0

The issue here is that console.log is present inside for loop.You should put console.log in your function which is removeCartItem

Try this:

function removeCartItem() {
    console.log("click");
}

var removeCartItemButtons = 
document.getElementsByClassName("btn-danger");
for (let i = 0; i < removeCartItemButtons.length; i++) {
    var button = removeCartItemButtons[i];
    button.addEventListener("click", removeCartItem);
}
0

At first the OP should focus on writing valid and also more semantic markup.

Secondly, the OP should make use of task-specific functions and event-delegation. The former enables code-reuse, the latter eases the OP's life if it comes to e.g. inserting cart-items into the DOM without having to take care again of each item's proper initialization/event-registration.

function handleCartClick({ target }) {
  // - event delegation, part II.

  //    - try accessing the task-specific target.
  const elmRemove = target.closest('.remove-item');
  if (elmRemove !== null) {

    //  - proceed with the task specific behavior.
    elmRemove
      .closest('.cart-item')
      .remove();
  }
}
function handleCartInput({ target }) {
  // - event delegation, part II.

  //    - try accessing the task-specific target.
  const elmInput = target.closest('input.batch-size');
  if (elmInput !== null) {

    //  - proceed with the task specific behavior.
    const elmOutput = elmInput
      .closest('.cart-item')
      .querySelector('output.total-price');

    const { productPrice, currencySymbol } = elmOutput.dataset;

    elmOutput.value = [

      currencySymbol,

      (Math.round(
        Number(elmInput.value) * Number(productPrice) * 100
      ) / 100).toFixed(2),

    ].join(' ');
  }
}

function initCart(rootNode) {
  // - event delegation, part I.

  //    - register the handling at the most
  //      task-related parent/root-element.
  rootNode
    .addEventListener('click', handleCartClick);
  rootNode
    .addEventListener('input', handleCartInput);

  //    - even re-use event-handler for computing
  //      the intial total value of each batch.
  rootNode
    .querySelectorAll('input.batch-size')
    .forEach(elmInput => 
      handleCartInput({ target: elmInput })
    );
}

// the cart-specific overal initialization task.
document
  .querySelectorAll('.cart-overview')
  .forEach(initCart);
body {
  margin: 0;
  zoom: .9;
}
figure, table.cart-overview td {
  margin: 0;
}
th, td {
  padding: 0 10px;
  text-align: left;
}
<table class="cart-overview">
  <thead>
    <tr>
      <th>Item</th>
      <th>Batch Size</th>
      <th>Total Price</th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr class="cart-item">
      <td class="product">
        <figure>
         <img src="https://t4.ftcdn.net/jpg/06/07/26/49/240_F_607264922_7Cc26iHMwiDtysAMFFRVV4fYktx62hgr.jpg"
              height="70"
              alt="T-shirt Contrast">
         <figcaption>T-shirt Contrast</figcaption>
        </figure>
      </td>
      <td>
        <input id="T-shirt-Contrast-batch"
               class="batch-size"
               type="number" min="0" max="300" value="2" step="1">
      </td>
      <td>
        <output for="T-shirt-Contrast-batch"
                class="total-price"
                data-product-price="29.99"
                data-currency-symbol="$">$ 0</output>
      </td>
      <td>
        <button type="button" class="remove-item">Remove Batch</button>
      </td>
    </tr>
    <tr class="cart-item">
      <td class="product">
        <figure>
         <img src="https://t3.ftcdn.net/jpg/06/17/92/38/240_F_617923806_CQRi5S9rfOFeQMVeUO97GUApKqSnqL8G.jpg"
              height="70"
              alt="T-shirt Colorblock">
         <figcaption>T-shirt Colorblock</figcaption>
        </figure>
      </td>
      <td>
        <input id="T-shirt-Colorblock-batch"
               class="batch-size"
               type="number" min="0" max="300" value="1" step="1">
      </td>
      <td>
        <output for="T-shirt-Colorblock-batch"
                class="total-price"
                data-product-price="45.55"
                data-currency-symbol="$">$ 0</output>
      </td>
      <td>
        <button type="button" class="remove-item">Remove Batch</button>
      </td>
    </tr>
  </tbody>
</table>
Peter Seliger
  • 11,747
  • 3
  • 28
  • 37
  • Very nice working solution. To let OP understand the problem, it would be good to also pinpoint exactly why OP's code doesn't work. Deepanshu's answer is better in that respect. – www.admiraalit.nl Aug 14 '23 at 06:43
  • As long as the OP does not provide the actual implementation of `removeCartItem` one only can guess what might be wrong with the OP's approach / code. The above provided solution does not participate in guessing, it instead focuses on introducing a better approach than registering the remove handler explicitly for/at every remove button. – Peter Seliger Aug 14 '23 at 07:57
-2

this might do the work (syntax sugar for chaining actions)

document.querySelectorAll(".btn-danger").forEach(el => { el.addEventListener('click', removeCartItem) })

// Update explanation

document.querySelectorAll(".btn-danger")

  • gets all the elements from document matching this selector - .btn-danger .forEach iterates through NodeList if any of results are there, and does not fail if the collection is empty.

el => { el.addEventListener('click', removeCartItem) })

this callback registers the click event listener to each element from the NodeList collection.

  • 1
    "*This might work*" is not an answer. Please explain how this possibly would solve the question/problem – DarkBee Aug 10 '23 at 11:41