Configure Cart Price Update

假装没事ソ 提交于 2019-12-13 07:20:56

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/11963896/configure-cart-price-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!