Scott Plunkett
Scott Plunkett

Reputation: 157

Configure Cart Price Update

I want to create a product ordering page that has tons of options. Each option changes the price around a little bit, and I want the total price auto-update whenever any option changes.

All options are Drop-down menus so the prices would need to change when they select an option from a drop down.

I'm open to everything, but simple code on one page would be best. I want to be able to edit the prices as a part of the rest of the product page as there is only one product.

Any advice would be appreciated.

Upvotes: 0

Views: 731

Answers (1)

Alex Kalicki
Alex Kalicki

Reputation: 1533

Try binding a jQuery/javascript function that calculates the sum of all price input fields and prints it at the bottom to the dropdowns' onchange events like so. The HTML I'm giving you is just a mockup, feel free to change it and the jQuery references to it as you wish.

HTML:

<p>Computer base price: $<span id="baseCost"></span></p>

<p>Select your upgrades:</p>
<form id="options">
    <select name="processor" onchange="calculateTotals()">
        <option value="Base_0">Base processor ($0)</option>
        <option value="Processor1_100">Processor 1 ($100)</option>
        <option value="Processor2_500">Processor 2 ($500)</option>
    </select>
    <select name="hard-drive" onchange="calculateTotals()">
        <option value="Base_0">Base hard-drive ($0)</option>
        <option value="7200rpm_250">7200rpm hard-drive ($250)</option>
    </select>
</form>

<p>Upgrade total: $<span id="upgradeCost">0</span></p><br>
<p>Final total: $<span id="sumTotal"></span></p>​

Javascript:

$(document).ready(function(){
    var basePrice = 2000;
    $("#baseCost").text(basePrice);
    $("#sumTotal").text(basePrice);
});

function calculateTotals(){
    var basePrice = parseInt($("#baseCost").text(), 10);
    var upgradePrice = 0;
    $("#options select").each(function(){
        var optionVal = $(this).val();
        upgradePrice += parseInt(optionVal.substr(optionVal.indexOf("_") + 1, optionVal.length - 1), 10);
    });
    $("#upgradeCost").text(upgradePrice);
    $("#sumTotal").text(basePrice + upgradePrice);
}​

WORKING DEMO

As you can see, the option value attributes include both the option ID and its price, separated by an underscore. This allows the Javascript and your form handling code to get both the selected options and their prices.

Upvotes: 1

Related Questions