Increment variable by more than 1?
Asked Answered
P

5

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.

Plovdiv answered 17/5, 2012 at 20:0 Comment(2)
v += 4...? And some padding...Edette
If you don't know how to add 4 to a number, I'd really suggest running through a basic programming tutorial.Bates
F
43

Use a compound assignment operator:

v += 4;
Flywheel answered 17/5, 2012 at 20:3 Comment(2)
Not equivalent: v += 4 only evaluates the expression once, which is good when it's a long expression or it has side effects.Lanham
v+=1 acts like ++v not v++Petty
L
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;
Lanham answered 17/5, 2012 at 20:2 Comment(3)
For reference: See Addition Assignment (+=) and Subtraction Assignment (-=) operators.Vergara
||= 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.Lynnett
You're right @Csit - I must have been thinking in a different language when I wrote this.Lanham
K
3

To increase v by n: v += n

Kaela answered 17/5, 2012 at 20:2 Comment(0)
C
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();
    }
Casiano answered 17/5, 2012 at 20:1 Comment(0)
S
-1

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

Soissons answered 15/3, 2020 at 4:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.