Search This Blog

javascript and jquery scenarios on a web page

Sales tax calculation

function addTax(subTotal, rate){
     // cannot pass a value by reference
     var taxAmt = subTotal*rate;
     var total = subTotal + taxAmt;
     // create an array if you want to return multiple values
     return [taxAmt, total];

$("#btnTotal").click(function(){
    // believe it or not I have found input type=text to work better than type=number when working
    // with numbers. The numbers type can contain hidden placeholers when inputing directly 
    // without using up and down click buttons. Convert your input data to numbers here.
    var sales = Number($("#sales").val());
    var tax = Number($("#tax").val());
    if(sales <= 0){
    alert("You must have positive sales in oreder to compute tax");
    return false;
    }

    $("#total").val(function(){
    //jquery lets you create an anonymous function for the val method
    //very powerful handle.  it reminds me of ruby codeblocks for collection objects and 
    //yield statements. So stuff your bag, but remember to return a value.
    var totals = addTax(sales, tax) ; 
    alert("Your tax is: " + totals[0].toFixed(2));  
    return totals[1].toFixed(2);
 });

No comments:

Post a Comment