Setting up Javascript order price minimum - javascript

I am trying to set up a way so that if my total cart's price is under $125, it will charge $125. I have googled multiple ways of getting the order minimum added but nothing works with how this code was set up. Please view the code below:
function Recalculate() {
var total = 0;
$.each(cart, function(index, item) {
var options = {};
if (item.o) $.each(item.o, function(opt_ind, opt_item) {
options[opt_item.name] = opt_item.value;
options[opt_item.id] = opt_item.value;
});
var width_ft = parseInt(options.width_ft);
if (!width_ft || isNaN(width_ft)) width_ft = 0;
var width_in = parseInt(options.width_in);
if (!width_in || isNaN(width_in)) width_in = 0;
var width = width_ft + width_in / 12;
var length_ft = parseInt(options.length_ft);
if (!length_ft || isNaN(length_ft)) length_ft = 0;
var length_in = parseInt(options.length_in);
if (!length_in || isNaN(length_in)) length_in = 0;
var sq = width * length;
var inshop = options.type_of_cleaning == 'In_Shop_Cleaning';
var base_price = 0;
var base_min = 0;
switch (item.p) {
case 'livingroom':
base_price = LIVING_ROOM;
break;
case 'stair':
base_price = STAIR;
break;
}
var i_total = sq * base_price;
if (i_total < base_min) i_total = base_min;
$('span.isize').eq(index).html('$' + i_total.toFixed(2));
total += i_total;
if (options.SCOTCHGARD == 'on') total += Math.min(sq * SCOTCHGARD, 25.00);
if (options.DECON == 'on') total += Math.min(sq * DECON, 25.00);
if (options.DA == 'on') total += Math.min(sq * DA, 25.00);
if (options.clean_or_buy == 'buy') total += i_total * NEW_PAD_TAX / 100;
});
return [total];
}

If you want to charge a minimum of $125, the simplest thing you could do is simply set the total to that minimum just before you return it. e.g.
if (total < 125) { total = 125; }
return total;
(Note that this is returning total not [total], as it is not clear to me why you want an array of a single value returned.)
Your question includes the phrase "...getting the order minimum added". That doesn't make sense to me, i.e. if the real total is $100, I doubt that you want to add $125 (to make $225 total), but rather you simply want to set the total to the minimum. If that is correct, but you do want to keep track of the extra that you add, then perhaps you could do the following, again right before you return from the function:
var extraForMinimum = 0;
if (total < 125) { extraForMinimum = 125 - total; }
return {total: total, extraForMinimum: extraForMinimum };
In this case, the function is returning an object that contains both the actual total (which could still be less than $125) as well as the extra cost that is required to bring the charge up to the minimum. If you are doing this, however, you might want to change the variable name from total to, say, subtotal or something else similar.

Related

How Do I Use Loops to Find Sums in Array?

So I need to use a loop to fill an array with the total amount. The total amount will be the amount spent plus a gift card that is a percentage. So
total = amountSpent + amountSpent*(1+giftCard)
I am having trouble getting the total. The spent and gift card amounts are all randomly generated using math.random. The spent and gift card amounts are each found in separate arrays, with the spent amount being anywhere between 0 to 500, and gift card amount being anywhere from 0 to 50.
var spent = new Array(5);
for (var i = 0; i < 5; i++)
{
randS = Math.floor(Math.random() * 500);
spent[i] = randS;
}
var gifts = new Array(5);
for (var i = 0; i < 5; i++)
{
randG= Math.floor(Math.random() * 50);
gifts[i] = randG;
}
These are how I fill the arrays using a for loop. I am now supposed to create a new array and use a loop to calculate the total. I defined 2 variables for spent and gift card amount, but I am unsure if they are calling the correct numbers.
var totals = new Array(5);
var tSpent = spent;
var tGifts = gifts;
for (var i = 0; i < 5; i++)
{
totals[i] = tSpent + (1 + (tGifts / 100)) * tSpent;
totals[i] = totals[i].toFixed(2);
}
I know this array is the problem since the other two arrays are displaying the numbers fine. I also have to convert the gift card amount to a decimal and make sure the total is to 2 decimal places.
you can write the whole code in one loop like this:
var spent=[],gifts=[],totals=[];
for(let i = 0; i < 5; i++){
spent[i] = Math.floor(Math.random() * 500);
gifts[i] = Math.floor(Math.random() * 50);
totals[i] = spent[i] + (1 + gifts[i]/10)*spent[i]
totals[i] = totals[i].toFixed(2);
}
As far as I am able to understand your question, I feel you are doing it correct, just a small correction needs to be done in your code.
var totals = new Array(5);
var tSpent = spent;
var tGifts = gifts;
for (var i = 0; i < 5; i++)
{
totals[i] = tSpent[i] + (1 + (tGifts[i] / 100)) * tSpent[i];
totals[i] = totals[i].toFixed(2);
}
Also, your arrays tSpend and tGifts are calling correct numbers, although they seem redundant, unless you have something planned for them later in code. If not, they are just directly referencing your actual variable spend and gifts.

Javascript addition giving me NaN

I have a Javascript code as written below. Everything is working fine except the fact the net value that is the grand total of addition of all the total values, is coming as NaN. I have used parseFloat() but still the result is NaN. But I am getting the all the total values.
Any help is welcome.
window.onkeyup=function() {
var items = document.querySelectorAll(".item");
var itemsArray = Array.prototype.slice.call(items,0);
var unit, rate, total, net, tax, margin, rateamount = 0;
itemsArray.forEach(function(el){
unit = el.querySelector('input[name="unit[]"]').value;
rate = el.querySelector('input[name="rate[]"]').value;
tax = el.querySelector('input[name="tax[]"]').value;
margin = el.querySelector('input[name="margin[]"]').value;
el.querySelector('input[id="marginrate[]"]').options[el.querySelector('input[id="marginrate[]"]').selectedIndex].text;
var rateMargin =el.querySelector('[name="marginrate[]"]').selectedIndex;
if (rateMargin==1) {rateamount=margin/100}
if (rateMargin==0) {rateamount=margin}
total = (parseFloat(unit * rate) + parseFloat(rateamount))-parseFloat(tax/100);
alert(total);
el.querySelector('input[name="total[]"]').value = total;
net+= parseFloat(total);
});
document.getElementById('net').value=net;
}
You never initialized net, so when you do net += parseFloat(total); you're adding a number to undefined, which results in NaN. You need to initialize it to 0.
You also should be calling parseFloat on the values that are read from the inputs, not on the results of arithmetic operations (they always return numbers, you don't need to parse them).
window.onkeyup = function() {
var items = document.querySelectorAll(".item");
var itemsArray = Array.prototype.slice.call(items, 0);
var unit, rate, total, net = 0, tax, margin, rateamount = 0;
itemsArray.forEach(function(el) {
unit = el.querySelector('input[name="unit[]"]').value;
rate = el.querySelector('input[name="rate[]"]').value;
tax = el.querySelector('input[name="tax[]"]').value;
margin = el.querySelector('input[name="margin[]"]').value;
el.querySelector('input[id="marginrate[]"]').options[el.querySelector('input[id="marginrate[]"]').selectedIndex].text;
var rateMargin = el.querySelector('[name="marginrate[]"]').selectedIndex;
if (rateMargin == 1) {
rateamount = margin / 100
} else if (rateMargin == 0) {
rateamount = margin
}
total = (parseFloat(unit) * parseFloat(rate) + parseFloat(rateamount)) - parseFloat(tax) / 100;
alert(total);
el.querySelector('input[name="total[]"]').value = total;
net += total;
});
document.getElementById('net').value = net;
}

How can I make the unique random numbers from this code appear on my page?

Someone showed me the following code which generates 3 random numbers between 1 and 10:
var limit = 10,
amount = 3,
lower_bound = 1,
upper_bound = 10,
unique_random_numbers = [];
if (amount > limit) limit = amount; //Infinite loop if you want more unique
//Natural numbers than exist in a
// given range
while (unique_random_numbers.length < limit) {
var random_number = Math.floor(Math.random()*(upper_bound - lower_bound) + lower_bound);
if (unique_random_numbers.indexOf(random_number) == -1) {
// Yay! new random number
unique_random_numbers.push( random_number );
}
}
//
How could I make these numbers appear in place of elements with a corresponding class? The code below is clearly wrong, but hopefully it illustrates what I'm trying to achieve:
<script type='text/javascript'>
var random_number1 = random_number1();
$('.random_number1').html(random_number1);
var random_number2 = random_number2();
$('.random_number2').html(random_number2);
</script>
<span class="random_number1"></span> <span class = "random_number2"></span>
assuming you had a div with id of numbers and the array unique_random_numbers, you'd populate it this way, assuming you have jquery reference:
for ( i = 0; i < unique_random_numbers.length; i++)
{
$("#Numbers").html($("#Numbers").html() +"<span>" + unique_random_numbers[i] + "</span><br/>");
}

Finding average from input array with Javascript - not calculating correctly

I am trying to calculate the average of 3 values (each numbered from 1-10) that are selected by the user and then pass the results to an text input (for display as a graph).
It should be updating the new average every time one of the values is changed, but the averaging is not working correctly at all. I think that the loop is not resetting the values every time it runs- it's adding up the sum each time it runs, but not sure how to fix it.
Here is my code:
var sliders = $("#health1,#health2,#health3");
var elmt = [];
$(sliders).each(function () {
elmt.push($(this).attr('value'));
$("#health1,#health2,#health3").change(function () {
var sum = 0;
averageRisk();
});
});
function averageRisk() {
var sum = 0;
for (var i = 0; i < elmt.length; i++) {
sum += parseInt(elmt[i], 10);
}
var avg = sum / elmt.length;
document.getElementById('healthLevel').value = +avg;
elmt.push($(sliders).attr('value'));
$('#healthLevel').val(avg).trigger('change');
console.log("Sum: " + sum);
console.log("Average: " + avg);
}
Here is an example:
http://jsfiddle.net/pixelmix/783cfmnv/
Not sure but seems like a lot of extra work going. Main issue was you were building array of initial values and not getting the values each time they changed. That first .each got all the slider values and added them to elmt and continued to push new values on to after every change instead of just getting the current values every time. Did you want to accumulate all values over time?
Fiddle: http://jsfiddle.net/AtheistP3ace/783cfmnv/6/
$("#health1,#health2,#health3").on('change', function () {
averageRisk();
});
function averageRisk() {
var sum = 0;
var elmt = $("#health1,#health2,#health3");
for (var i = 0; i < elmt.length; i++) {
sum += parseInt(elmt[i].value, 10); //don't forget to add the base
}
var avg = sum / elmt.length;
document.getElementById('healthLevel').value = +avg;
$('#healthLevel').val(avg).trigger('change');
console.log("Sum: " + sum);
console.log("Average: " + avg);
}
And as pointed out if you want to ignore updating things when the sum is NaN you can do this:
function averageRisk() {
var sum = 0;
var elmt = $("#health1,#health2,#health3");
for (var i = 0; i < elmt.length; i++) {
sum += parseInt(elmt[i].value, 10); //don't forget to add the base
}
if (isNaN(sum)) {
return false;
}
var avg = sum / elmt.length;
document.getElementById('healthLevel').value = +avg;
$('#healthLevel').val(avg).trigger('change');
console.log("Sum: " + sum);
console.log("Average: " + avg);
}
The problem is that you fill the elmt array at page loading.
When user changes the values, you do not refresh the elmt array. So the array used to compute the average is always the same, empty.
You have to recover the input values each time they are modified.
function averageRisk() {
var sum = 0;
// Re make the loop for getting all inputs values
$(sliders).each(function() {
var value = parseInt($(this).val(), 10);
sum += value;
});
var avg = sum/$(sliders).length;
$('#healthLevel').val(avg);
}
Working example : http://jsfiddle.net/783cfmnv/7/
PS : You can use the css class healthInput to select your inputs. If you add later other fields, you will not have to add the new input id to your jQuery selector.
I did this work, check it .
http://jsfiddle.net/783cfmnv/10/
$("#health1,#health2,#health3").change(function() {
var val1 = +slider1.val();
var val2 = +slider2.val();
var val3 = +slider3.val();
var avg = (val1 + val2 + val3) /3;
$("#healthLevel").val(avg);
});

Divide a function value by a number

I want to be able to take the value from the calcOrderTotal input and then divide it and display the divided output in another input (for example, to show the Order Total price, and then what the order total 36 monthly lease price would be). I sort of attempted to do it with the "calc36Month" function, but I know it's not right.
function calcOrderTotal() {
var orderTotal = 0;
var productSubtotal = $("#product-subtotal").val() || 0;
var serverPrice = $('.server-radio:checked').val() || 0;
var equipmentPrice = $('.equipment-radio:checked').val() || 0;
var underTotal = $("#under-box").val() || 0;
var orderTotal = parseFloat(CleanNumber(productSubtotal)) + parseFloat(CleanNumber(serverPrice)) + parseFloat(CleanNumber(equipmentPrice));
$("#order-total").val(CommaFormatted(orderTotal));
$("#fc-price").attr("value", orderTotal);
}
The calcOrderTotal function is then redirected to this HTML input and displays a dollar value (this does work):
<input type="text" class="total-box" value="$0" id="order-total" disabled="disabled" name="order-total"></input>
I want to be able to take the OrderTotal dollar value and divide it by 36 months and input the 36 month lease value into another input. Here is an example of what I'm looking for (I know this does not work):
function calc36Month() {
var 36Month = 0;
var orderTotal = $("#order-total").val() || 0;
var 36Month = parseFloat(CleanNumber(orderTotal)) / 36;
$("#36-monthly-total").val(CommaFormatted(36Month));
$("#fc-price").attr("value", 36Month);
}
How can I do this?
Here ya go:
function calcOrderTotal() {
var orderTotal = 0;
var productSubtotal = $("#product-subtotal").val() || 0;
var serverPrice = $('.server-radio:checked').val() || 0;
var equipmentPrice = $('.equipment-radio:checked').val() || 0;
var underTotal = $("#under-box").val() || 0;
var orderTotal = parseFloat(CleanNumber(productSubtotal)) + parseFloat(CleanNumber(serverPrice)) + parseFloat(CleanNumber(equipmentPrice));
$("#order-total").val(CommaFormatted(orderTotal));
$("#fc-price").attr("value", orderTotal);
if (orderTotal > 0) {
calcMonthly(orderTotal);
}
}
EDIT: Edited per request.
function calcMonthly(total) {
var pmt1 = total / 36;
var pmt2 = total / 24;
var pmt3 = total / 12;
$("#monthly-36").val(CommaFormatted(pmt1));
$("#monthly-24").val(CommaFormatted(pmt2));
$("#monthly-12").val(CommaFormatted(pmt3));
//$("#fc-price").attr("value", pmt1); // what is the purpose of this?
}
Avoid using numeric digits as variable names, element ID's or CSS classes, or beginning any of the aforementioned references with a number. Begin all variable names, ID's and classes with a letter.

Categories