calculate total price from checkbox + select list - javascript

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;
}

Related

How to know if one of the checkboxes is selected with Javascript

I have many checkboxes with prices. I want that every time the user selects a checkbox, the final price is updated. I have done it with JQuery but the function is never entered.
$('input[type=checkbox]:checked').on('change', function() {
console.log("Hi")
var total = 0;
var result = document.getElementById('result');
if ($('checkbox1').prop("checked")) {
total += 100;
}
if ($('checkbox2').prop("checked")) {
total += 50;
}
if ($('checkbox3').prop("checked")) {
total += 250;
}
result.innerText = 'Result: ' + total + '€';
});
HTML:
<input type="checkbox" name="myCheckbox" id="checkbox1" value="yes"/> 7:30h-21:00h - 250€
<div id="result"><p>Result: </p></div>
I would also like to know if there is something like:
$('input[type=checkbox]:checked').on('change', function() || $('#num').on("keyup", function() {
Because I want it to enter the function whether a checkbox has been selected or if it has selected a number in the input:number.
I think .on() function in jQuery's newer version is obsolete now try this way.
$('input[type="checkbox"]').change(function () {
console.log("Hi")
var total = 0;
var result = document.getElementById('result');
if ($('checkbox1').prop("checked")) {
total += 100;
}
if ($('checkbox2').prop("checked")) {
total += 50;
}
if ($('checkbox3').prop("checked")) {
total += 250;
}
result.innerText = 'Result: ' + total + '€';
});

Javascript to calculate and display odds as their simplest fraction

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>

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 % 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