Javascript to calculate and display odds as their simplest fraction - javascript

I'm writing a bit of script for the WooCommerce product page that takes the quantity entered in the qty input field and displays some text based on that qty:
function reduce(numerator,denominator){
var gcd = function gcd(a,b){
return b ? gcd(b, a%b) : a;
};
gcd = gcd(numerator,denominator);
return [numerator/gcd,denominator/gcd];
}
jQuery('.qty').on('change', function() {
showOdds();
});
function showOdds() {
var qty = 1; // hard coded for testing
var min = 200; // hard coded for testing
var sofar = 40; // hard coded for testing
var plural = '';
var total = 0;
var odds = '';
if (qty > 1){
plural = 'tickets';
}
else{
plural = 'ticket';
}
if (qty > 0){
if ((qty + sofar) > min){
total = qty + sofar;
odds = reduce(qty, total);
}
else {
odds = reduce(qty, min);
}
var text = document.createElement('p');
text.className = 'product-odds';
text.innerHTML = 'Max odds of ' + qty + ' ' + plural + ' winning is ' + odds + '.';
var theDiv = document.getElementById('odds');
theDiv.appendChild(text);
}
}
jQuery(document).ready(function loadPage() {
showOdds();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='odds'></div>
The current output:
Max odds of 1 ticket winning is 1,200
How can I make the odds display in their simplest fraction form? For example if there are 200 tickets available and '1' is entered, it should show '1/200' but if someone enters '20' it should show '1/10'. The 'total' figure will eventually be picked up from the page rather than a fixed value too.
I can use the gcd as posted here but how can I get the two numbers from the array and display them as a fraction (with the /) in the required div?

You can return the desired string instead of array. Check the snippet below.
I've changed return [numerator/gcd,denominator/gcd]; to return numerator/gcd+'/'+denominator/gcd;
function reduce(numerator,denominator){
var gcd = function gcd(a,b){
return b ? gcd(b, a%b) : a;
};
gcd = gcd(numerator,denominator);
return numerator/gcd+'/'+denominator/gcd;
}
jQuery('.qty').on('change', function() {
showOdds();
});
function showOdds() {
var qty = 1; // hard coded for testing
var min = 200; // hard coded for testing
var sofar = 40; // hard coded for testing
var plural = '';
var total = 0;
var odds = '';
if (qty > 1){
plural = 'tickets';
}
else{
plural = 'ticket';
}
if (qty > 0){
if ((qty + sofar) > min){
total = qty + sofar;
odds = reduce(qty, total);
}
else {
odds = reduce(qty, min);
}
var text = document.createElement('p');
text.className = 'product-odds';
text.innerHTML = 'Max odds of ' + qty + ' ' + plural + ' winning is ' + odds + '.';
var theDiv = document.getElementById('odds');
theDiv.appendChild(text);
}
}
jQuery(document).ready(function loadPage() {
showOdds();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='odds'></div>

Related

Can't determine reason for NaN output

first time asking a question, long-time lurker. Entry CS student here, first semester working with HTML and JS, and am working on a project that essentially checks the value of some checkboxes, radio buttons, and textboxes, formats some variables based on inputs and values, and outputs that information in a display section. The major issue being, my .js script is resulting in an output in NaN in places I would expect a number and I can't determine as to why. Below is the script, I can amend the html page as well if needed.
But Essentially, in the displayOutput function, the ranging from accessoriesOut to amountOut are giving me a display of NaN and I'm at a loss.
// Declares global variables and their default values.
const STEREO_COST=425.76;
const INTERIOR_COST=987.41;
const NAVIGATION_COST=1741.23;
const STANDARD_FINISH=0;
const PEARLIZED_FINISH=345.72;
const CUSTOM_FINISH =599.99;
const EXCELLENT_CONDITION=1.0;
const GOOD_CONDITION=0.9;
const FAIR_CONDITION=0.8;
const POOR_CONDITION=0.6;
const SALES_TAX_RATE=0.08;
const TRADE="trade";
const ACCESSORIES="accessories";
const SUBTOTAL="subtotal";
const TAX="tax";
const AMOUNT="amount";
const PRICE="price";
const NAME="name";
// Establishes pricing and condition values with the corresponding user inputs.
function pageLoad(){
document.getElementById("stereoDiv").innerHTML += FormatCurrencyText(STEREO_COST);
document.getElementById("interiorDiv").innerHTML += FormatCurrencyText(INTERIOR_COST);
document.getElementById("navigationDiv").innerHTML += FormatCurrencyText(NAVIGATION_COST);
document.getElementById("standardDiv").innerHTML += FormatCurrencyText(STANDARD_FINISH);
document.getElementById("pearlizedDiv").innerHTML += FormatCurrencyText(PEARLIZED_FINISH);
document.getElementById("customDiv").innerHTML += FormatCurrencyText(CUSTOM_FINISH);
document.getElementById("excellentDiv").innerHTML += FormatPercentText(EXCELLENT_CONDITION);
document.getElementById("goodDiv").innerHTML += FormatPercentText(GOOD_CONDITION);
document.getElementById("fairDiv").innerHTML += FormatPercentText(FAIR_CONDITION);
document.getElementById("poorDiv").innerHTML += FormatPercentText(POOR_CONDITION);
}
// Formats money value for output.
function FormatCurrency(amt){
return "$" + amt.toFixed(2); }
// Formats the output and text for currency.
function FormatCurrencyText(amt){
return " (" + FormatCurrency(amt) + ")"; }
// Formats the percent values for display.
function FormatPercentText(pct){
return " (" + (pct * 100).toFixed(2) +"%)"; }
// Determines which trade-in choice is made, and assigns it to and returns a variable.
function getConditionRate() {
var rate;
if (document.getElementById("excellent").checked==true){
rate=EXCELLENT_CONDITION; }
if (document.getElementById("good").checked==true){
rate=GOOD_CONDITION; }
if (document.getElementById("fair").checked==true){
rate=FAIR_CONDITION; }
if (document.getElementById("poor").checked==true){
rate=POOR_CONDITION; }
return rate; }
// Determines which accessories are selected, accumulates and returns a total.
function getAccessoriesTotal() {
var total;
if (document.getElementById("stereo").checked==true){
total += parseFloat(STEREO_COST); }
if (document.getElementById("interior").checked==true){
total += parseFloat(INTERIOR_COST); }
if (document.getElementById("navigation").checked==true){
total += parseFloat(NAVIGATION_COST); }
return total; }
// Determines which finish choice is made, assigns it to a variable for return.
function getFinishAmount(){
var amount;
if (document.getElementById("standard").checked==true){
amount = parseFloat(STANDARD_FINISH); }
if (document.getElementById("pearlized").checked==true){
amount = parseFloat(PEARLIZED_FINISH); }
if (document.getElementById("custom").checked==true){
amount = parseFloat(CUSTOM_FINISH); }
return amount; }
// Determines whether a trade-in was selected, enables/disables controls accordingly.
function EnableTradeIn(){
var isChecked = document.querySelector('[id="tradein"]:checked');
if (isChecked) {
document.getElementById("excellent").disabled=false;
document.getElementById("good").disabled=false;
document.getElementById("fair").disabled=false;
document.getElementById("poor").disabled=false;
document.getElementById("tradeinBox").disabled=false; }
else {
document.getElementById("excellent").disabled=true;
document.getElementById("good").disabled=true;
document.getElementById("fair").disabled=true;
document.getElementById("poor").disabled=true;
document.getElementById("tradeinBox").disabled=true;
document.getElementById("excellent").focus();
document.getElementById("tradeinBox").value=""; }
}
//
function DisplayOutput(accessoriesTotal, tradeinAllowance, subtotal, taxAmount, amountDue, price, name) {
document.getElementById("nameOut").innerHTML=name;
document.getElementById("priceOut").innerHTML=FormatCurrency(price);
document.getElementById("accessoriesOut").innerHTML=FormatCurrency(accessoriesTotal);
document.getElementById("tradeinOut").innerHTML=FormatCurrency(tradeinAllowance);
document.getElementById("subtotalOut").innerHTML=FormatCurrency(subtotal);
document.getElementById("salestaxOut").innerHTML=FormatCurrency(taxAmount);
document.getElementById("amountOut").innerHTML=FormatCurrency(amountDue);
}
function CalculateMain(){
var accessoriesTotal = 0;
var tradeinAllowance = 0;
var subtotal = 0;
var taxAmount = 0;
var amountDue = 0;
var isTradein;
var conditionRate = 0;
var tradeinAmount = 0;
var conditionRate = 0;
var price = document.getElementById("priceBox").value;
var name = document.getElementById("nameBox").value;
//Validate that name is entered
if (name == "" || document.getElementById("nameBox").value==undefined){
document.getElementById("nameError").style.border="1px solid red";
document.getElementById("nameError").innerHTML = "No name entered";
return; }
else{
document.getElementById("nameError").style.border="";
document.getElementById("nameError").innerHTML = ""; }
//Validate price
if (isNaN(price) || price == "" || price < 0){
document.getElementById("priceError").style.border="1px solid red";
document.getElementById("priceError").innerHTML = "Price is not valid";
return; }
else {
price = parseFloat(price);
document.getElementById("priceError").style.border="";
document.getElementById("priceError").innerHTML = "";
}
//Determine if there is a trade-in
isTradein = document.getElementById("tradein").checked;
if (isTradein) {
tradeinAmount = parseFloat(document.getElementById("tradeinBox").value);
conditionRate = getConditionRate(); }
//Validate trade in amount
if (isNaN(tradeinAmount) || tradeinAmount == "" || tradeinAmount < 0) {
document.getElementById("tradeinError").style.border = "1px solid red";
document.getElementById("tradeinError").innerHTML = "Tradein amount is not valid";
return; }
else {
document.getElementById("tradeinError").style.border = "";
document.getElementById("tradeinError").innerHTML = ""; }
//Calculate trade-in allowance (will be 0 if check box is not checked)
tradeinAllowance = parseFloat(tradeinAmount) * parseFloat(conditionRate);
//Validate trade in allowance is not greater than price
if (tradeinAllowance > price){
document.getElementById("tradeinError").style.border="1px solid red";
document.getElementById("tradeinError").innerHTML = "Trade in more than Price";
return; }
else {
document.getElementById("tradeinError").style.border="";
document.getElementById("tradeinError").innerHTML = "";
}
accessoriesTotal = getAccessoriesTotal() + getFinishAmount();
subtotal = price + accessoriesTotal - tradeinAllowance;
taxAmount = subtotal * SALES_TAX_RATE;
amountDue = subtotal + taxAmount;
//Call DisplayOutput
DisplayOutput(parseFloat(accessoriesTotal), parseFloat(tradeinAllowance), parseFloat(subtotal), parseFloat(taxAmount), parseFloat(amountDue), price, name);
}
In the getAccessoriesTotal function, you don't have total defined before trying to add to it. I assume you'd want to default it to 0. (Note: I'd also recommend defaulting amount in getFinishAmount to something).
function getAccessoriesTotal() {
var total = 0;
if (document.getElementById("stereo").checked==true){
total += parseFloat(STEREO_COST); }
if (document.getElementById("interior").checked==true){
total += parseFloat(INTERIOR_COST); }
if (document.getElementById("navigation").checked==true){
total += parseFloat(NAVIGATION_COST); }
return total;
}

Solve mathematical function in javascript

I have created this function for a shopping basket. To be simple, i have x products with (2 checkbox + quantity input) for each.
The first checkbox add +3, second +8, to the product price. It's like (3+8+price)*quantity. At the end of the page, i have the total result (like product1 + product2...Etc)
The problem is: If i'm posting the form with new quantities, and going back to the page, i have the default result (total price) (of course, checkbox are checked + new quantity with PHP).
Here is my function:
$(function(){
var item_prices = 0;
var total_item_prices = 0;
var total_unique_item_prices = 0;
var total_price = 0;
$.each($('*[data-item-price]'), function(index, element) {
var item_price = $(element).data("item-price");
total_unique_item_prices = parseInt($('[data-total]').html()) + item_price;
total_price = total_unique_item_prices;
$('[data-total]').html(total_unique_item_prices);
})
$.each($('*[data-item-price]'), function(index, element) {
var item_price = $(element).data("item-price");
var price_of_options = 0;
var quantity = parseInt($(element).find('input[data-quantity]').val());
$.each($(element).children().find("[data-price]"), function(index, element2) {
$(element2).click(function(){
var actual_price = parseInt($('[data-total]').html());
var actual_item_price = parseInt($(element).find('[data-item-total]').html());
var price = $(element2).data("price");
if ($(element2).is(':checkbox') && $(element2).is(':checked')) {
price_of_options += price;
$(element).find('[data-item-total]').html(actual_item_price + (price * quantity));
$('[data-total]').html(actual_price + (price * quantity));
}
else {
price_of_options -= price;
$(element).find('[data-item-total]').html(actual_item_price - (price));
$('[data-total]').html(actual_price - (price * quantity));
}
})
})
$(element).find('input[data-quantity]').bind('keyup mouseup', function () {
var new_quantity = parseInt($(element).find('input[data-quantity]').val());
var quantity_dif = new_quantity - quantity;
var actual_price = parseInt($('[data-total]').html());
if (quantity_dif > 0) {
quantity_dif = new_quantity - quantity;
$(element).find('[data-item-total]').html((item_price + price_of_options) * new_quantity);
$('[data-total]').html(actual_price + ((item_price + price_of_options) * quantity_dif));
}
else {
quantity_dif *= -1;
quantity = parseInt($(element).find('[data-quantity]').val());
$(element).find('[data-item-total]').html((item_price + price_of_options) * new_quantity);
$('[data-total]').html(actual_price - ((item_price + price_of_options) * quantity_dif));
}
quantity = parseInt($(element).find('[data-quantity]').val());
})
})
})
As I said, code is working: https://jsfiddle.net/redbean/4dy38ye4/1/ Just not when i'm reloading the webpage.
I'm not english, be kind about this. I'm trying to do the best to be clear!

calculate total price from checkbox + select list

i want to calculate the total price from select list + checkboxes
this code showing the price of selected element from the list "tvs":
<script type="text/javascript">
$(document).ready(function () {
var cheap = false;
$('#tvs').change(function () {
var price = parseFloat($('.total').data('base-price')) || 0;
$('#tvs').each(function (i, el) {
price += parseFloat($('option:selected', el).data(cheap ? 'cheap' : 'price'));
console.log('x', price)
$('.total').val(price.toFixed(2) + '' + '$');
});
});
});
</script>
<input placeholder="0.00$" style=" width: 65px; border: 0px;" class="total" data-base-price="0" readOnly>
and this code showing the price of checked checkboxes:
<script type="text/javascript">
function update_amounts_modal() {
var sum = 0.0;
$('form').each(function () {
var qty = $(this).find('.qty').val();
var price = $(this).find('.price').val();
var isChecked = $(this).find('.idRow').prop("checked");
if (isChecked){
qty = parseInt(qty, 10) || 0;
price = parseFloat(price) || 0;
var amount = (qty * price);
sum += amount;
}
});
$('.total-modal').text(sum.toFixed(2) + ' ' + '$');
$().ready(function () {
update_amounts_modal();
$('form .qty, form .idRow').change(function () {
update_amounts_modal();
});
});
</script>
<div id="subusers" class="total-modal">0.00 $</div>
Hey #musa94 I assume you have a fairly large application and you separate your code into files and what to find a way to sum up two values from different chunks of code. A easy way without changing too much of your existing code is to define a shared data object that holds the values that you want to handle through out your application. You can sum the value from the list and checkbox up by accessing the values in the data object.
// define a data object that exists in your application
window.__ = window.__ || { data: { total: 0, modal: 0 } };
$(document).ready(function () {
var cheap = false;
$('#tvs').change(function () {
var total = getTvsTotal(cheap);
// update your view
$('.total').val(total.toFixed(2) + '' + '$');
// update your data object
__.data.total = total;
console.log('review data object', __);
});
});
$(document).ready(function () {
$('form .qty, form .idRow').change(function () {
var total = update_amounts_modal();
$('.total-modal').text(total.toFixed(2) + ' ' + '$');
__.data.modal = total;
console.log('review data object', __);
});
});
/**
* calculate your tvs total
* #param {boolean}
* #return {number}
*/
function getTvsTotal(cheap) {
var price = parseFloat($('.total').data('base-price')) || 0;
$('#tvs').each(function (i, el) {
price += parseFloat($('option:selected', el).data(cheap ? 'cheap' : 'price'));
console.log('list total:', price);
});
return price;
}
/**
* calculate your amounts modal
* #return {number}
*/
function update_amounts_modal() {
var sum = 0.0;
$('form').each(function () {
var qty = $(this).find('.qty').val();
var price = $(this).find('.price').val();
var isChecked = $(this).find('.idRow').prop("checked");
var amount;
if (isChecked){
qty = parseInt(qty, 10) || 0;
price = parseFloat(price) || 0;
amount = qty * price;
sum += amount;
}
console.log('sum:', sum);
});
return sum;
}

Calculate % from number generated

I have code which calculates 8% of the number entered, so for example is in the code below. If you enter "1" in the first box" and "100" in the second box the Total Refund (including 8%) = 108
JavaScript code:
$(document).ready(function() {
var sum = 0;
function calcSum(prevVal) {
var val1 = $('#val1').val();
var val2 = $('#val2').val();
var val3 = $('#val3').val();
var val4 = $('#val4').val();
this.sum = parseFloat(val1) * parseFloat(val2) + parseFloat(val3) * parseFloat(val4);
return this.sum;
}
var subAmt = $("#sub"),
taxAmt = $("#tax"),
totAmt = $("#total");
$(".val").each(function() {
var prevVal = this.value / 1,
self = this;
$(this).keyup(function() {
subAmt.val(calcSum.call(self, prevVal));
totAmt.val(this.sum + this.sum * parseFloat(taxAmt.val() / 100));
prevVal = self.value;
});
});
});
JSFiddle.
What I would like to do is to calculate 20% of the 8% in the second to the bottom box. So in this example the answer should be 1.60.
Then I would like to show in the total box 106.40 (108 - 1.60).
Why won't you just extract the tax (the 8%) to a separate variable? Something like this?
var taxDelta = this.sum*parseFloat(taxAmt.val()/100);
Then you can freely add it to the total:
totAmt.val(this.sum + taxDelta);
And calculate 20% of it if needed:
var addTax = taxDelta * taxAVal;

jQuery Calculations - How to trigger multiple discount conditions based on totals sent to one quantity field

Issue:
The problem is that when a customer inputs a product quantity say over 10, 50, 100 or 200 the price drop should occur on all of the products - not just the one line where the quantity is set. See this fiddle: http://jsfiddle.net/freedawirl/fucd6k64/
Question:
How do I re-wire the form to trigger discount conditions based on the overall quantity field, which gets its value from an individual product quantity field? The trick then would be that for each of the product unit prices, the breakpoints would all get triggered simultaneously as a result of the overall quantity written from (var n15_qty_total_b).
// Variables for the Business form
var n15_qty_1b = $('.n15_qty_1b').val();
var n15_qty_2b = $('.n15_qty_2b').val();
var n15_qty_3b = $('.n15_qty_3b').val();
var n15_qty_4b = $('.n15_qty_4b').val();
var n15_p_1b_single_price
var n15_p_2b_single_price
var n15_p_3b_single_price
var n15_p_4b_single_price
var n15_total_price_1b = $('.n15_total_price_1b').val();
var n15_total_price_2b = $('.n15_total_price_2b').val();
var n15_total_price_3b = $('.n15_total_price_3b').val();
var n15_total_price_4b = $('.n15_total_price_4b').val();
n15_total_price_1b = n15_total_price_1b.replace("$", "");
n15_total_price_2b = n15_total_price_2b.replace("$", "");
n15_total_price_3b = n15_total_price_3b.replace("$", "");
n15_total_price_4b = n15_total_price_4b.replace("$", "");
var n15_total_price_b
var n15_qty_total_b
var n15_subtotal_price_b
var n15_processing
var n15_final_price_b
// Variables for both forms
var n15_processing = 12.00;
//First row Local 31Day Pass
$('.n15_qty_1b').on('change', function() {
n15_qty_1b = $('.n15_qty_1b').val();
// Setting discount break points
if (n15_qty_1b < 10 ) {
n15_p_1b_single_price = 33.00;
};
if (n15_qty_1b >= 10 && n15_qty_1b <= 50 ) {
n15_p_1b_single_price = 29.70;
};
if (n15_qty_1b > 50 && n15_qty_1b < 200 ) {
n15_p_1b_single_price = 28.00;
};
if (n15_qty_1b >= 200 ) {
n15_p_1b_single_price = 26.40;
};
$('.n15_single_price_1b').val('$' + n15_p_1b_single_price.toFixed(2));
n15_total_price_1b = n15_qty_1b * n15_p_1b_single_price;
($(this).closest("tr").find('.n15_total_price_1b').val('$' + n15_total_price_1b.toFixed(2)));
// Code to update the total QTY
n15_qty_total_b = Number(n15_qty_1b) + Number(n15_qty_2b) + Number(n15_qty_3b) + Number(n15_qty_4b);
$('.n15_qty_total_b').val(n15_qty_total_b);
// Getting and Setting the Subtotal Price
n15_subtotal_price_b = Number(n15_total_price_1b) + Number(n15_total_price_2b) + Number(n15_total_price_3b) + Number(n15_total_price_4b)
$('.n15_subtotal_price_b').val('$' + n15_subtotal_price_b.toFixed(2))
// Getting and Setting the GrandTotal Price
n15_final_price_b = Number(n15_subtotal_price_b) + Number(n15_processing);
$('.n15_final_price_b').val('$' + n15_final_price_b.toFixed(2));
});
// Second table row Premium 31Day Pass
$('.n15_qty_2b').on('change', function() {
n15_qty_2b = $('.n15_qty_2b').val();
// Setting discount break points
if (n15_qty_2b < 10 ) {
n15_p_2b_single_price = 49.50;
};
if (n15_qty_2b >= 10 && n15_qty_2b <= 50 ) {
n15_p_2b_single_price = 44.55;
};
if (n15_qty_2b > 50 && n15_qty_2b < 200 ) {
n15_p_2b_single_price = 42.00;
};
if (n15_qty_2b >= 200 ) {
n15_p_2b_single_price = 39.60;
};
$('.n15_single_price_2b').val('$' + n15_p_2b_single_price.toFixed(2));
n15_total_price_2b = n15_qty_2b * n15_p_2b_single_price;
($(this).closest("tr").find('.n15_total_price_2b').val('$' + n15_total_price_2b.toFixed(2)));
// Code to update the total QTY
n15_qty_total_b = Number(n15_qty_1b) + Number(n15_qty_2b) + Number(n15_qty_3b) + Number(n15_qty_4b);
$('.n15_qty_total_b').val(n15_qty_total_b);
// Getting and Setting the Subtotal Price
n15_subtotal_price_b = Number(n15_total_price_1b) + Number(n15_total_price_2b) + Number(n15_total_price_3b) + Number(n15_total_price_4b)
$('.n15_subtotal_price_b').val('$' + n15_subtotal_price_b.toFixed(2))
// Getting and Setting the Total Price
n15_final_price_b = Number(n15_subtotal_price_b) + Number(n15_processing);
$('.n15_final_price_b').val('$' + n15_final_price_b.toFixed(2));
});
// Third row Commuter 31Day Pass
$('.n15_qty_3b').on('change', function() {
n15_qty_3b = $('.n15_qty_3b').val();
// Setting quantity breakpoints for bulk discount
if (n15_qty_3b < 10 ) {
n15_p_3b_single_price = 77.00;
};
if (n15_qty_3b >= 10 && n15_qty_3b <= 50 ) {
n15_p_3b_single_price = 62.00;
};
if (n15_qty_3b > 50 && n15_qty_3b < 200 ) {
n15_p_3b_single_price = 62.00;
};
if (n15_qty_3b >= 200 ) {
n15_p_3b_single_price = 62.00;
};
// Set the amount of quantity
$('.n15_single_price_3b').val('$' + n15_p_3b_single_price.toFixed(2));
// get the total price for row 3
n15_total_price_3b = n15_qty_3b * n15_p_3b_single_price;
// set total price for row 3
($(this).closest("tr").find('.n15_total_price_3b').val('$' + n15_total_price_3b.toFixed(2)));
// Code to update the total QTY
n15_qty_total_b = Number(n15_qty_1b) + Number(n15_qty_2b) + Number(n15_qty_3b) + Number(n15_qty_4b);
$('.n15_qty_total_b').val(n15_qty_total_b);
// Getting and Setting the Subtotal Price
n15_subtotal_price_b = Number(n15_total_price_1b) + Number(n15_total_price_2b) + Number(n15_total_price_3b) + Number(n15_total_price_4b)
$('.n15_subtotal_price_b').val('$' + n15_subtotal_price_b.toFixed(2))
// Getting and Setting the Total Price
n15_final_price_b = Number(n15_subtotal_price_b) + Number(n15_processing);
$('.n15_final_price_b').val('$' + n15_final_price_b.toFixed(2));
});
// Fourth row Reduced Fare Pass
$('.n15_qty_4b, .n15_single_price_4b').on('change', function() {
// Getting the quantity input
n15_qty_4b = $('.n15_qty_4b').val();
// Getting the single price input and replacing the $ sign
n15_p_4b_single_price = $('.n15_single_price_4b').val();
n15_p_4b_single_price = n15_p_4b_single_price.replace("$", "");
// Setting the total price
n15_total_price_4b = n15_qty_4b * n15_p_4b_single_price;
$('.n15_total_price_4b').val('$' + n15_total_price_4b.toFixed(2));
// Code to update the total QTY
n15_qty_total_b = Number(n15_qty_1b) + Number(n15_qty_2b) + Number(n15_qty_3b) + Number(n15_qty_4b);
$('.n15_qty_total_b').val(n15_qty_total_b);
// Getting and Setting the Subtotal Price
n15_subtotal_price_b = Number(n15_total_price_1b) + Number(n15_total_price_2b) + Number(n15_total_price_3b) + Number(n15_total_price_4b)
$('.n15_subtotal_price_b').val('$' + n15_subtotal_price_b.toFixed(2))
// Getting and Setting the Total Price
n15_final_price_b = Number(n15_subtotal_price_b) + Number(n15_processing);
$('.n15_final_price_b').val('$' + n15_final_price_b.toFixed(2));
});
You can write a function that checks the total quantity and gives a discount based on the appropriate break points. Run the function each time you update the total quantity, so in your case, whenever one of the individual quantities change.
Declare the following function in between the first and second blocks of your code and then call the function in each of your .on('change') listeners before you update the values in html. Obviously you will have to fill out the rest of your breakpoints.
var checkTotalQuantity = function(){
if (n15_qty_total_b > someBreakPoint){
n15_price_total_b *= 0.85 //15% discount for the total price
}
}

Categories