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>
one big problem i see here is your
iftaxvariable 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:
this way, it will be accessible whereever you need it…
update
as for the content not showing in the divs, don’t use
it won’t work for two different reasons:
first:
.value = ...(.val(...)in jQuery) is native javascript and won’t work in a jQuery objectsecond: 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: