jQuery / js - Calculate tax, subtotal and total based on state and quantity select options

Go To StackoverFlow.com

0

I'm new to js/jQuery. Forgive this horrible script. I'm lost.

*(Updated with global variable ifTaxRate as suggested.)*

I'm trying to calculate tax, subtotal, and total based on a customer's selected state and quantity ordered and dynamically display it onscreen.

If a customer is from Idaho, I'm trying to apply a 6% sales tax rate.

Select Options:

 <select id="state" value="<?php echo $_SESSION['sstate'] ?>" name="state" class="required" >
   <option value="">Select State</option>
   <option value="AK">Alaska</option>
   .
   <option value="ID">Idaho</option>
   .
   .
   <option value="WY">Wyoming</option>
</select>

<select id="orderquantity" name="orderquantity">
   <option value="1">1 Bottle (30 Day Supply)</option>
   .
   .
   <option value="8">8 Bottles (240 Day Supply)</option>
</select>

Divs to display info:

<div class="quantityselected"></div>
<div class="productprice"></div>
<div class="pricequantity"></div>
<div class="subtotal"></div>
<div class="tax"></div>
<div class="shipping"></div>
<div class="total"></div>

Really bad js attempt:

<script type="text/javascript">
      var ifTaxRate;
      $(document).ready(function() {
          $("#state").change(function() {
            if ($(this).val() == 'ID') {
              ifTaxRate = .06;
            } else {
              ifTaxRate = 0;
            }
          });
        });

      function doMath() {
            var quant = parseInt(document.getElementById('orderquantity').value);
            //change price here
            var price = 69.99;
            var tax = ifTaxRate;
            //change flat shipping cost here
            var shipping = 4.99;
            var subtotal = quant * price;
            var taxtotal = tax * subtotal;
            var total = subtotal + tax;

            $('.quantityselected').value = quant;
            $('.productprice').value = price;
            $('.pricequantity').value = subtotal;
            $('.tax').value = taxtotal;
            $('.shipping').value = shipping;
            $('.total').value = shipping;
        }
</script>
2012-04-05 17:12
by chasemb


1

one big problem i see here is your iftax variable is declared inside the scope of the anonymous function you pass as a parameter on $('state').change();
You have to declare it as a global variable, and not redeclare it inside said function:

var ifTaxRate = 0; //new    
$(document).ready(function() {
   $("#state").change(function() {
      if ($(this).val() == 'ID') {
         ifTaxRate = .06;
      } else {
         ifTaxRate = 0;
      }
      doMath();//new
   });
   //this way every time you change a select box value, doMath() is called
   $('select').change(doMath);
});

this way, it will be accessible whereever you need it...

update

as for the content not showing in the divs, don't use

$('.quantityselected').value = quant;

it won't work for two different reasons: first: .value = ... (.val(...) in jQuery) is native javascript and won't work in a jQuery object
second: value is a property of input and select controls, with divs you have to set .innerText (.text() in jQuery) and .innerHTML (.html() in jQuery)

use:

$('.quantityselected').html(quant);
... 
2012-04-05 17:19
by André Alçada Padez
I've tried this as suggested by Steve and Andrzej, however, all my divs are still blank. I've checked the script in chrome and it's passing - chasemb 2012-04-05 17:26
no prob, i have looked at the source of the page, and nowhere i find the function doMath() being invoked. When do you want to update the divs? on change of the state - André Alçada Padez 2012-04-05 17:54
I'd like the div's to update when a). the state selected is Idaho and b). they change the inital quantity of 1 to something else and reflect those changes on screen. Like I said, I'm super new to js... : - chasemb 2012-04-05 17:58
ok, so what you have to do, is call doMath() everytime something like that happens; i update my cod - André Alçada Padez 2012-04-05 17:59
try it now, pleas - André Alçada Padez 2012-04-05 18:01
It's updated but still blank divs - chasemb 2012-04-05 18:04
there is an error on your javascript. remove ' }); ' before the line i adde - André Alçada Padez 2012-04-05 18:06
and also, you have to replace all ifTax for ifTaxRat - André Alçada Padez 2012-04-05 18:11
It's working now :) Thanks so much! Can it display a default amount before they select a state or order quantity? Would I just set a default amount for each variable - chasemb 2012-04-05 18:15
see my update. - André Alçada Padez 2012-04-05 18:16


0

Your problem is likely to be one of scope.

Since you're declaring the variable iftax inside the state-change function's closure, it's not visible from your doMath method.

Inside you should declare the variable at the top level, and then merely assign to it from the state-change function:

<script type="text/javascript">
  var iftax;

  $(document).ready(function() {
      $("#state").change(function() {
        if ($(this).val() == 'ID') {
          iftax = .06;
        } else {
          iftax = 0;
        }
      });
    });

    // rest as before

(On a completely different topic, calling the variable ifTaxRate or similar would IMHO be clearer, since at the moment I think it could be confused with the amount of tax due, especially when used ni the same context as price and shipping.)

2012-04-05 17:16
by Andrzej Doyle
Hmmm. I've made the changes but nothing is shown on screen. All the divs are blank.. - chasemb 2012-04-05 17:22
ok, i will see the rest of the cod - André Alçada Padez 2012-04-05 17:28
I've made the updates above - chasemb 2012-04-05 17:29


0

The variable "iftax" declared in the document ready function is local to that function. The iftax referred to in the doMath function would look at global scope (window.iftax), and I'm guessing that is undefined.

Although using global variables is a bit of an anti-pattern, if you remove the "var" from all the places in the document ready function (where it is currently written "var iftax"), it will default to a global variable and your code should work.

2012-04-05 17:17
by Steve H.
Ads