0

I have some code on a page for a cart system with the following:

<div class="number-input">
<button onclick="this.parentNode.querySelector('input[type=number]').stepDown();preventDefault(); updateCartItems('2371') " ></button>
<input class="quantity" id="addQuantity-2371"  min="1" name="cart_quantity[]" value="5" step="1" type="number">
<button onclick="$(this).prev()[0].stepUp();preventDefault(); updateCartItems('2371') " class="plus">
</button>
</div>

I am looking to call a function, in addition to changing the displayed value:

function updateCartItems(itemId) { // begin document ready
    var products_id = parseInt(itemId);
    var quantity = document.getElementById('addQuantity-' + itemId);
    if (quantity) {
      var cart_quantity = parseInt(quantity.value);
    } else {
      var cart_quantity = parseInt(1);
    };
    $.ajax({
      url: 'ajax_add_saved_product.php',
      method: "post",
      dataType : "html",
      data: {cart_quantity, products_id},
      success: function (response, textStatus, jqXHR) {
         alert(response);
         $('#cartData').html(response);
         update_cart_total();
         update_free_products();
         update_shipping_estimate();
      },
       error: function (jqXHR, textStatus, errorThrown) {
         alert(xhr.responseText);
        },
    });
 };

Issue is that I am not calling the updateCartItems function. Am I doing the call correctly?

Peter
  • 51
  • 7
  • 1
    Consider a change in design; use jQuery to attach your event handlers using event delegation instead of using HTML attributes like `onclick` then it would just be a matter of adding a line to your event listener. – Heretic Monkey May 04 '22 at 17:47
  • Sounds good, not sure how to go about that though as I am not that adept at javascript. – Peter May 04 '22 at 17:49
  • What do the other functions do? `$(this).prev()[0].stepUp();preventDefault(); ` My bet is that one of them is preventing `updateCartItems()` from running. – mykaf May 04 '22 at 17:53
  • The idea behind event delegation is outlined in the answers to [Event binding on dynamically created elements?](https://stackoverflow.com/q/203198/215552) – Heretic Monkey May 04 '22 at 17:53
  • That part of the code basically is a quantity counter that increases or decreases the quantity. – Peter May 04 '22 at 17:55
  • Check the console for errors. I suspect preventDefault is undefined, it's normally a method of the event object which you aren't accessing. – James May 04 '22 at 18:04

0 Answers0