开发者

How to have jQuery auto-calculate and display the total of some form values?

(I'm fairly new to jQuery.)

I have a traditional HTML form with 3 drop-down selection options (each option has different values in which I'd like to total up.) As of now, I'm using a jQuery code (below) that multiplies "os0, os1, os2" and then displays the totalCost in the "result" css block just fine, but it requires the user to click the "Calculate Total" button.

$(document).ready(function() {
    $('#calculateTotal').click(function() {
    var unitPrice = 2, paperTypes = 2, printedSides = 2;
    var inputNum_of_Shirts = $('#os0').val();
    var inputNum_of_FColor = $('#os1').val();
    var inputNum_of_BColor = $('#os2').val();
    var totalCost = (inputNum_of_Shirts*parseFloat(unitPrice))
        *(parseFloat(paperTypes)*inputNum_of_FColor)
        *(parseFloat(printedSides)* inputNum_of_BCo开发者_JAVA百科lor );
    var perShirtCost = (parseFloat(unitPrice))
        *(parseFloat(paperTypes)*inputNum_of_FColor)
        *(parseFloat(printedSides)*inputNum_of_BColor);

    $('#total').html(formatCurrency(totalCost));
    $('#perShirt').html(formatCurrency(perShirtCost));
    $('#result').css('display', 'block');
    document.getElementById("finalpaypal").value = totalCost;
});
});

Is there a way to have jQuery update this total automatically? Without a "Calculate Total" button? Any help of any kind would be greatly appreciated.

Thanks, Aaron


Since you already have the calculation in place, move the logic into a seperate function and then bind it to on change event of each select:

Try this:

function calculateTotal(){
   var unitPrice = 2, paperTypes = 2, printedSides = 2;
    var inputNum_of_Shirts = $('#os0').val();
    var inputNum_of_FColor = $('#os1').val();
    var inputNum_of_BColor = $('#os2').val();
    var totalCost = (inputNum_of_Shirts*parseFloat(unitPrice))
        *(parseFloat(paperTypes)*inputNum_of_FColor)
        *(parseFloat(printedSides)* inputNum_of_BColor );
    var perShirtCost = (parseFloat(unitPrice))
        *(parseFloat(paperTypes)*inputNum_of_FColor)
        *(parseFloat(printedSides)*inputNum_of_BColor);

    $('#total').html(formatCurrency(totalCost));
    $('#perShirt').html(formatCurrency(perShirtCost));
    $('#result').css('display', 'block');
    document.getElementById("finalpaypal").value = totalCost;
}

   $(function(){
     $('#os0, #os1, #os2').change(calculateTotal);
   }); 


I'd suggest attaching an jquery event listener to the 3 dropdowns so that when any of them are changed, the total value is recalculated. You could choose to either wait until all three have values or just 'as people go'.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜