Question

I'm working on a SimpleCart project that requires many options that alter the price of an item. Each option adds a certain amount to the base price of the item. For example:

item base price = $10

dropdown menu 1:

  • options 1,2,3 add $0
  • options 4,5,6 add $1
  • options 7,8,9 add $2

...and so on for multiple dropdown menus in multiple items with differing base prices.

The simplecartjs.org documentation suggests a beforeAdd event such as this:

simpleCart.bind( 'beforeAdd' , function( item ){
if( item.get( 'size' ) == 'Small' ){
item.price( 10 );
} else if( item.get( 'size' ) == 'Large' ){
item.price( 12 );
}
});

How would you use something similar to this to add a specific amount to the base price rather than defining a set price for each option?

Here is some simplified sample HTML code (my project actually has 70+ options in one drop-down):

<div class="simpleCart_shelfItem">
<h2 class="item_name">item</h2>
<select class="item_size">
<option value="small">small</option>
<option value="medium">medium</option>
<option value="large">large</option>
</select>
<select class="item_length">
<option value="short">short</option>
<option value="long">long</option>
</select>
<input value="1" class="item_Quantity" type="text">
<span class="item_price">$10</span>
<a class="item_add" href="javascript:;">add to cart</a></p>
</div>
Was it helpful?

Solution

I would probably go about it the same way as the documentation supplied does, but with the addition of making the base price a variable that you can use to add your additional costs. Applying the variable inside the function will keep it localized so if you have a base price in another function it will not bother the code.

*Note I didn't test it, just a thought of how I would give it a go.

simpleCart.bind('beforeAdd', function (item) {
    var basePrice = 10;
    if (item.get('size') == 'Small') {
        item.price(basePrice + 2);
    } else if (item.get('size') == 'Large') {
        item.price(basePrice + 2);
    } else if (item.get('size') == 'Long' && item.get('otherProperty')) {
        item.price(basePrice + 9);
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top