19

Here's my script :

function itemQuantityHandler(operation, cart_item) {
  var v = cart_item.quantity;

  //add one
  if (operation === 'add' && v < settings.productBuyLimit) {
    v++;
  }

  //substract one
  if (operation === 'subtract' && v > 1) {
    v--;
  }

  //update quantity in shopping cart
  $('.item-quantity').text(v);

  //save new quantity to cart
  cart_item.quantity = v;
}

What I need is to increase v (cart_item.quantity) by more than one. Here, it's using v++, but it's only increasing by 1. How can I change this to make it increase by 4 every time I click on the plus icon?

I tried

v++ +4

But it's not working.

Ivar
  • 6,138
  • 12
  • 49
  • 61
larin555
  • 1,669
  • 4
  • 28
  • 43

5 Answers5

43

Use a compound assignment operator:

v += 4;
helpermethod
  • 59,493
  • 71
  • 188
  • 276
22

Use variable += value; to increment by more than one:

v += 4;

It works with some other operators too:

v -= 4;
v *= 4;
v /= 4;
v %= 4;
v <<= 1;
v >>= 4;
We Are All Monica
  • 13,000
  • 8
  • 46
  • 72
  • For reference: See [Addition Assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators#Addition_assignment) (`+=`) and [Subtraction Assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators#Subtraction_assignment) (`-=`) operators. – showdev Aug 05 '15 at 20:52
  • ||= and &&= don't seem to exist in JavaScript. |= and &= perform bitwise assignment operators which are just as good if you're not doing direct === comparisons to actual booleans. – Edwin Feb 04 '17 at 00:16
  • You're right @Csit - I must have been thinking in a different language when I wrote this. – We Are All Monica Feb 27 '17 at 07:38
3

To increase v by n: v += n

Kvam
  • 2,148
  • 1
  • 20
  • 32
0

Try this:

//event handler for item quantity in shopping cart
    function itemQuantityHandler(p, a) {
        //get current quantity from cart
        var filter = /(\w+)::(\w+)/.exec(p.id);
        var cart_item = cart[filter[1]][filter[2]];
        var v = cart_item.quantity;


        //add four
        if (a.indexOf('add') != -1) {
            if(v < settings.productBuyLimit) v += 4;
        }
        //substract one
        if (a.indexOf('subtract') != -1) {
            if (v > 1) v--;

        }
        //update quantity in shopping cart
        $(p).find('.item-quantity').text(v);
        //save new quantity to cart
        cart_item.quantity = v;
        //update price for item
      $(p).find('.item-price').text((cart_item.price*v).toFixed(settings.numberPrecision));
        //update total counters 
        countCartTotal();
    }
c.hill
  • 3,127
  • 25
  • 31
-1

var i = 0; function buttonClick() { x = ++i*10 +10; }

Flavio
  • 1