0

I'm populating my cart using ajax. Within the cart I've got a quantity field with a plus and minus button. This is the code for the buttons:

  <div class="cart-quantity">
                <input type='button' value='+' class='qtyplus CartCount' field='updates_{{ item.id }}' />
<input name="updates[]" id="updates_{{ item.id }}" class="quantity CartCount" value="{{ item.quantity }}" />
      <input type='button' value='-' class='qtyminus CartCount' field='updates_{{ item.id }}' />
  </div>

And here is the javascript to update the quantity field via the plus/minus button:

// This button will increment the value
$('.qtyplus').on("click", function(){
    // Stop acting like a button

    // Get the field name
    fieldName = $(this).attr('field');
    // Get its current value
    var currentVal = parseInt($('input[id='+fieldName+']').val());
    // If is not undefined
    if (!isNaN(currentVal)) {
        // Increment
        $('input[id='+fieldName+']').val(currentVal + 1);
    } else {
        // Otherwise put a 0 there
        $('input[id='+fieldName+']').val(0);
    }
    e.preventDefault();
$(this).closest('form').submit();
});
// This button will decrement the value till 0
$(".qtyminus").on("click",function() {
    // Stop acting like a button

    // Get the field name
    fieldName = $(this).attr('field');
    // Get its current value
    var currentVal = parseInt($('input[id='+fieldName+']').val());
    // If it isn't undefined or its greater than 0
    if (!isNaN(currentVal) && currentVal > 0) {
        // Decrement one
        $('input[id='+fieldName+']').val(currentVal - 1);
    } else {
        // Otherwise put a 0 there
        $('input[id='+fieldName+']').val(0);
    }
    e.preventDefault();
$(this).closest('form').submit();
});

As you can see I've tried changing the click event to on click but it's still not working. Any ideas?

Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
MariaL
  • 1,112
  • 2
  • 16
  • 41

1 Answers1

3

Instead of binding the click event to the .qtyplus directly, try with:

$(document).on('click', '.qtyplus', function() { /* ... */ });

For the better performance, instead of binding it to document, use the closest .qtyplus elements parent.

hsz
  • 148,279
  • 62
  • 259
  • 315
  • Yes, dynamically loaded objects won't respond to events unless you bind to the $(document), or some other parent that is loaded before the listener was registered. – bcr666 Aug 09 '18 at 14:26
  • Literally just came across this in another post, thanks anyway! – MariaL Aug 09 '18 at 14:28