I am absolutely stumped, I have been working on this for weeks and have come to the conclusion that my knowledge is too limited to figure this out
ok, I have a page in my customer portal where employees can enter end of day sales reports. The first half of the page is input fields with dollar amounts and profits calculated by a percentage. Funny thing is it works on my website but not on jsfiddle.
the second part is a devices sold section using selects and calculations for price, cost and profit
there are 2 parts to the script and it gets crazy when I put them together, they dont work at all
I tried to post the entire page and script here but it was too long
here is the script
function Adder() {
var ppc = parseFloat(document.form.ppc.value);
var tmo = parseFloat(document.form.tmo.value);
var cf = parseFloat(document.form.cf.value);
var act = parseFloat(document.form.act.value);
var fla = parseFloat(document.form.fla.value);
var misc = parseFloat(document.form.misc.value);
var exp = parseFloat(document.form.exp.value);
var prof1 = parseFloat(document.form.prof1.value);
var prof2 = parseFloat(document.form.prof2.value);
var prof3 = parseFloat(document.form.prof3.value);
var prof4 = parseFloat(document.form.prof4.value);
var prof5 = parseFloat(document.form.prof5.value);
var result1 = ppc * 0.12;
document.form.prof1.value = result1.toFixed(2);
var result2 = tmo * 0.015;
document.form.prof2.value = result2.toFixed(2);
var result3 = cf * 0.21;
document.form.prof3.value = result3.toFixed(2);
var result4 = act * 35;
document.form.prof4.value = result4.toFixed(2);
var result5 = fla * 60;
document.form.prof5.value = result5.toFixed(2);
var result6 = ppc + tmo + cf + prof4 + prof5 + misc - exp;
document.form.sum1.value = result6.toFixed(2);
var result7 = prof1 + prof2 + prof3 + prof4 + prof5 + misc - exp;
document.form.total1.value = result7.toFixed(2);
}
var item = document.getElementById('item');
var item1 = document.getElementById('item1');
var item2 = document.getElementById('item2');
var item3 = document.getElementById('item3');
var item4 = document.getElementById('item4');
var item5 = document.getElementById('item5');
var item6 = document.getElementById('item6');
item.onchange = function () {
price.innerHTML = "$" + this.value;
cost.innerHTML = "$" + (this[this.selectedIndex].getAttribute('value2'));
qty.value = 1; //Order 1 by default.
add();
};
qty.onchange = function () {
add();
};
item1.onchange = function () {
price1.innerHTML = "$" + this.value;
cost1.innerHTML = "$" + (this[this.selectedIndex].getAttribute('value2'));
qty1.value = 1; //Order 1 by default.
add();
};
qty1.onchange = function () {
add();
};
item2.onchange = function () {
price2.innerHTML = "$" + this.value;
cost2.innerHTML = "$" + (this[this.selectedIndex].getAttribute('value2'));
qty2.value = 1; //Order 1 by default.
add();
};
qty2.onchange = function () {
add();
};
item3.onchange = function () {
price3.innerHTML = "$" + this.value;
cost3.innerHTML = "$" + (this[this.selectedIndex].getAttribute('value2'));
qty3.value = 1; //Order 1 by default.
add();
};
qty3.onchange = function () {
add();
};
item4.onchange = function () {
price4.innerHTML = "$" + this.value;
cost4.innerHTML = "$" + (this[this.selectedIndex].getAttribute('value2'));
qty4.value = 1; //Order 1 by default.
add();
};
qty4.onchange = function () {
add();
};
item5.onchange = function () {
price5.innerHTML = "$" + this.value;
cost5.innerHTML = "$" + (this[this.selectedIndex].getAttribute('value2'));
qty5.value = 1; //Order 1 by default.
add();
};
qty5.onchange = function () {
add();
};
item6.onchange = function () {
price6.innerHTML = "$" + this.value;
cost6.innerHTML = "$" + (this[this.selectedIndex].getAttribute('value2'));
qty6.value = 1; //Order 1 by default.
add();
};
qty6.onchange = function () {
add();
};
function add() {
var inputs = document.getElementsByTagName('input');
var selects = document.getElementsByTagName('select');
var total = 0;
var taxes = 0;
for (var i = 0; i < selects.length; i++) {
var sum = 0;
var price = (parseFloat(selects[i].value)) ? parseFloat(selects[i].value) : 0;
var cost = (parseFloat(selects[i][selects[i].selectedIndex].getAttribute('value2'))) ? parseFloat(selects[i][selects[i].selectedIndex].getAttribute('value2')) : 0;
var qty = (parseFloat(inputs[i].value)) ? parseFloat(inputs[i].value) : 0;
sum += (price - cost) * qty;
total += sum;
if (i === 0) {
document.getElementById('result').innerHTML = "$" + sum.toFixed(2);
} else {
document.getElementById('result' + i).innerHTML = "$" + sum.toFixed(2);
}
}
document.getElementById('total').innerHTML = "$" + total.toFixed(2);
}
and the jsfiddle for everything together, I just cant figure it out
Related
The program will ask for all inputs and print everything but the variables all come up as undefined.
This is for a web application tied to a HTML document. No errors are thrown when it runs.
function driver(){
var plan1Code = "S";
var plan1Cost = 450;
var plan1Hours = 2.5;
var plan1Pics = 75;
var plan2Code = "G";
var plan2Cost = 750;
var plan2Hours = 5;
var plan2Pics = 125;
var plan3Code = "P";
var plan3Cost = 1000;
var plan3Hours = 8;
var plan3Pics = 225;
var retName = getName();
var retPlan = getPlan();
var retHours = getHours();
var retPics = getPics();
var baseCost, totalCost, upchargeTime, upchargeTimeCost, upchargePics, upchargePicsCost;
if (retPlan == plan1Code){
baseCost = plan1Cost;
upchargeTime, upchargeTimeCost = calcTimeUpcharge(retHours, plan1Hours);
upchargePics, upchargePicsCost = calcPicsUpcharge(retPics, plan1Pics);
}
else if (retPlan == plan2Code){
baseCost = plan2Cost;
upchargeTime, upchargeTimeCost = calcTimeUpcharge(retHours, plan2Hours);
upchargePics, upchargePicsCost = calcPicsUpcharge(retPics, plan2Pics);
}
else if (retPlan == plan3Code){
baseCost = plan3Cost;
upchargeTime, upchargeTimeCost = calcTimeUpcharge(retHours, plan3Hours);
upchargePics, upchargePicsCost = calcPicsUpcharge(retPics, plan3Pics);
}
totalCost = calcTotalCost(baseCost, upchargeTimeCost, upchargePicsCost);
print(retName, retPlan, baseCost, upchargeTime, upchargeTimeCost, upchargePics, upchargePicsCost, totalCost);
}
function getName(){
var text;
var name = prompt("Enter your name");
if (name == null) {
text = "Please enter a valid name";
}
}
function getPlan(plan){
var plan = prompt("Enter the selected package");
}
function getHours(hours){
var hours = prompt("Enter anticipated coverage hours");
}
function getPics(pics){
var pics = prompt("Enter anticipated number of pictures");
}
function calcTimeUpcharge(hours, baseHours){
upchargeTime = hours - baseHours;
var price;
if (upchargeTime>0){
var upchargeTimeUnits = Math.ceil((upchargeTime)/.5);
upchargeTimeCost = upchargeTimeUnits * 50;
}
else {
upchargeTime = 0;
upchargeTimeCost = 0;
}
return upchargeTime, upchargeTimeCost;
}
function calcPicsUpcharge(pics, basePics){
upchargePics = pics - basePics;
if (upchargePics>0){
upchargePicsunits = Math.ceil((upchargePics)/10);
upchargePicsCost = upchargePicsunits*40;
}
else {
upchargePics = 0;
upchargePicsunits = 0;
}
return upchargePics, upchargePicsCost;
}
function calcTotalCost(baseCost, timeCost, picsCost){
return baseCost + timeCost + picsCost;
}
function print(retName, retPlan, baseCost, upchargeTime, upchargeTimeCost, upchargePics, upchargePicsCost, totalCost){
document.write(retName + ", thanks for using Photosarus!" + "\n");
document.write("<br><br>");
document.write("You selected plan " + retPlan + " at a cost of "+ baseCost );
document.write("<br><br>");
document.write(upchargeTime + "additional hours at a cost of "+ upchargeTimeCost);
document.write("<br><br>");
document.write(upchargePics + "additional pictures at a cost of "+ upchargePicsCost);
}
I expect the output to say
Bill, thanks for using Photosarus!
You selected plan S at a cost of $450
0 additional hours at a cost of $0
0 additional pictures at a cost of $0
But instead I get
undefined, thanks for using Photosarus!
You selected plan undefined at a cost of undefined
undefined additional hours at a cost of undefined
undefined additional pictures at a cost of undefined
You need to return the values from the functions:
function getName(){
var text;
var name = prompt("Enter your name");
if (name == null) {
text = "Please enter a valid name";
}
return name;
}
function getPlan(plan){
var plan = prompt("Enter the selected package");
return plan;
}
function getHours(hours){
var hours = prompt("Enter anticipated coverage hours");
return hours;
}
function getPics(pics){
var pics = prompt("Enter anticipated number of pictures");
return pics;
}
my javascript isn't the best. I have some code here in the form of a calculator:
https://jsfiddle.net/yadL05aL/
my javascript:
// Get a list of your products and pop them into a dropdownlist
function GetProducts() {
var products = V12.getFinanceProducts();
var ddlProducts = document.getElementById('productsList');
for (var i = 0; i < products.length; i++) {
var newItem = new Option(products[i].name, products[i].productId);
ddlProducts.appendChild(newItem);
}
}
// Get details of repayments for the product selected
function CalculateRepayments() {
var productId = $('#productsList').val(); // selected product
var financeProduct = V12.getFinanceProduct(productId); // get the object
var cashPrice = $('#cashPrice').val();
var depositFactor = $('#deposit').val();
var deposit = cashPrice * (depositFactor / 100);
var payments = V12.calculate(financeProduct, cashPrice, deposit);
PopulateDescription(payments);
}
function UpdateLoanInfo() {
$('#cashPrice').val($('#cpRange').val());
$('#deposit').val($('#depRange').val());
CalculateRepayments();
}
// Show repayment plan details in the description
function PopulateDescription(payments) {
$('#lblFinalPayment').html('');
$('#lblDeposit').html('£' + payments.deposit);
$('#lblInitPayments').html('£' + payments.initialPayments);
$('#lblTotalRepayable').html('£' + payments.amountPayable);
$('#lblInterest').html(payments.apr + '%');
if (payments.initialPayments != payments.finalPayment && payments.finalPayment > 0) {
$('#lblMonths').html(payments.months - 1);
$('#lblFinalPayment').html(' and a final payment of £' + payments.finalPayment);
} else {
$('#lblMonths').html(payments.months);
}
}
// Firing this will loop through your V12 products and grab the product with the lowest
// possible monthly payments.
function GetLowestMonthlyPayments() {
var products = V12.getFinanceProducts();
var lowestMonthlyPayment = 0;
var lowestMonthlyPaymentProductId = 0;
for (var i = 0; i < products.length - 1; i++) {
var product = V12.getFinanceProduct(products[i].productId);
var cashPrice = $('#cashPrice').val();
var depositFactor = $('#deposit').val();
var deposit = cashPrice * (depositFactor / 100);
var payments = V12.calculate(product, cashPrice, deposit);
var monthlyPayment = payments.initialPayments;
if (parseFloat(lowestMonthlyPayment) > parseFloat(monthlyPayment) || lowestMonthlyPayment == 0) {
lowestMonthlyPayment = payments.initialPayments;
lowestMonthlyPaymentProductId = product.productId;
}
}
$("#productsList").val(lowestMonthlyPaymentProductId);
CalculateRepayments();
}
// Ready up our events
(function ($) {
GetProducts();
CalculateRepayments();
$('#productsList').on('change', function () {
CalculateRepayments();
});
$('#cpRange, #depRange').on("input", function () {
UpdateLoanInfo();
});
$('#lowestMonthlyPayments').click(function () {
GetLowestMonthlyPayments();
});
$('#cashPrice, #deposit').keyup(function () {
var cp = $('#cashPrice').val();
var dep = $('#deposit').val();
$('#cpRange').val(cp);
$('#depRange').val(dep);
CalculateRepayments();
});
//spinner//
$('<div class="quantity-nav"><div class="quantity-button quantity-up">+</div><div class="quantity-button quantity-down">-</div></div>').insertAfter('.quantity input');
$('.quantity').each(function() {
var spinner = jQuery(this),
input = spinner.find('input[type="number"]'),
btnUp = spinner.find('.quantity-up'),
btnDown = spinner.find('.quantity-down'),
min = input.attr('min'),
max = input.attr('max');
btnUp.click(function() {
var oldValue = parseFloat(input.val());
if (oldValue >= max) {
var newVal = oldValue;
} else {
var newVal = oldValue + 100;
}
spinner.find("input").val(newVal);
spinner.find("#cpRange").val(cp);
spinner.find("#depRange").val(dep);
spinner.find("input, #cashPrice").trigger("change");
});
btnDown.click(function() {
var oldValue = parseFloat(input.val());
if (oldValue <= min) {
var newVal = oldValue;
} else {
var newVal = oldValue - 100;
}
spinner.find("input").val(newVal);
spinner.find("input").trigger("change");
});
});
})(jQuery);
what I am trying to achieve is when you click on the plus and minus buttons in the cash price input, the bottom labels reflect the decrease or increment changes to the deposit / monthly repayments & APR.
Can anyone please point me in the right direction?
Kind regards
Robbie
I'm having a problem when trying to multiply the totalPallets by the price-per-pallet ($25) and then showing that in the productSubTotal box. With the code as it is right now, the quatity total shows but when I try to get the price result, it doesn't show the operation. Also, if I try changing anythung from the code, the whole thing breaks down. I'll be thankful if anyone could help me. Thanks
// UTILITY FUNCTIONS
function IsNumeric(n) {
return !isNaN(n);
}
function calcTotalPallets() {
var totalPallets = 0;
$(".num-pallets-input").each(function() {
var thisValue = parseInt($(this).val());
if ( (IsNumeric(thisValue)) && (thisValue != '') ) {
totalPallets += parseInt(thisValue);
};
});
$("#quantitytotal").val(totalPallets);
}
function calcProdSubTotal() {
var prodSubTotal = 0;
$(".totalprice").each(function() {
var valString = parseInt(totalPallets) * multiplier;
prodSubTotal += parseInt(valString);
});
$("#product-subtotal").val(CommaFormatted(prodSubTotal));
};
// "The Math" is performed pretty much whenever anything happens in the quanity inputs
$('.num-pallets-input').bind("focus blur change keyup", function(){
// Caching the selector for efficiency
var $el = $(this);
// Grab the new quantity the user entered
var numPallets = CleanNumber($el.val());
var totalPallets = CleanNumber($el.val());
var prodSubTotal = CleanNumber($el.val());
// Find the pricing
var multiplier = $el
.parent().parent()
.find("td.price-per-pallet span")
.text();
};
// Calcuate the overal totals
calcProdSubTotal();
calcTotalPallets();
});
function CommaFormatted(amount) {
var delimiter = ",";
var i = parseInt(amount);
if(isNaN(i)) { return ''; }
i = Math.abs(i);
var minus = '';
if (i < 0) { minus = '-'; }
var n = new String(i);
var a = [];
while(n.length > 3)
{
var nn = n.substr(n.length-3);
a.unshift(nn);
n = n.substr(0,n.length-3);
}
if (n.length > 0) { a.unshift(n); }
n = a.join(delimiter);
amount = "$" + minus + n;
return amount;
}
});
i have my invoice js script done and working, but i cant figure out how to round the grand total to 2 decimal spaces.
js:
var item = document.getElementById('item');
var item1 = document.getElementById('item1');
var item2 = document.getElementById('item2');
var item3 = document.getElementById('item3');
item.onchange = function() {
price.innerHTML = "$" + this.value;
qty.value = 1; //Order 1 by default.
add();
};
qty.onchange = function() {
add();
}
item1.onchange = function() {
price1.innerHTML = "$" + this.value;
qty1.value = 1; //Order 1 by default.
add();
};
qty1.onchange = function() {
add();
}
item2.onchange = function() {
price2.innerHTML = "$" + this.value;
qty2.value = 1; //Order 1 by default.
add();
};
qty2.onchange = function() {
add();
}
item3.onchange = function () {
price3.innerHTML = "$" + this.value;
qty3.value = 1; //Order 1 by default.
add();
};
qty3.onchange = function() {
add();
}
function add() {
var inputs = document.getElementsByTagName('input');
var selects = document.getElementsByTagName('select');
var total = 0;
for (var i = 0; i < selects.length; i++) {
var sum = 0;
var price = (parseFloat(selects[i].value) )?parseFloat(selects[i].value):0;
var qty = (parseFloat(inputs[i].value) )?parseFloat(inputs[i].value):0;
sum += price * qty;
total += sum * 1.06
if(i == 0){
document.getElementById('result').innerHTML = "$" + sum;
}else{
document.getElementById('result'+i).innerHTML = "$" + sum;
}
};
document.getElementById('Total').innerHTML = "$" + total;
}
ive tried 3 or 4 methods, but due to my lack of experience with js, i just cant get right
Use:
.toFixed(2);
on the grand total
Like:
1.23898.toFixed(2); // 1.24
Do you want smt like this: 1.23756 -> 1.24 ?
Then you can use toFixed(num)
var num = 1.23756;
console.log(num.toFixed(2)); // 1.24
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
Try this:
Convert a number into a string, keeping only two decimals:
var num = 5.56789;
var n=num.toFixed(2);
The result of n will be:
5.57
I'm struggling to see why I'm getting NaN in my local file, but in my fiddle it works perfectly.
I've checked to see if I've left out any id's in the HTML but it all looks in order. I can't see why it is returning NaN.
Here is a part of my JavaScript which I think is causing the problem:
function updateCost() {
var amount = parseFloat(document.getElementById("amount").value) || 0.00,
delivery = parseFloat(document.getElementById("delivery").value),
total = amount + delivery,
fixedrate = total / 100 * 12.2,
grandtotal = fixedrate + total;
document.getElementById("amountdiv").innerHTML = amount.toFixed(2);
document.getElementById("deliverydiv").innerHTML = delivery.toFixed(2);
document.getElementById("total").innerHTML = total.toFixed(2);
document.getElementById("fixedrate").innerHTML = fixedrate.toFixed(2);
document.getElementById("grandtotal").innerHTML = grandtotal.toFixed(2);
}
// handle the due date
var dayNames = new Array("Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday");
var monthNames = new Array("January","February","March","April","May","June","July", "August","September","October","November","December");
var todayPlus30 = new Date();
todayPlus30.setDate(todayPlus30.getDate()+30)
var dateStr = (dayNames[todayPlus30.getDay()] + ", " + monthNames[todayPlus30.getMonth()+1] + " " + todayPlus30.getDate() + ", " + todayPlus30.getFullYear());
$('#date').html(dateStr);
$(function(){
document.getElementById("amount").onchange =
document.getElementById("delivery").onchange = updateCost;
});
$(document).ready(function(){
$('#amount').change(function(){ updateCost(); });
$('#delivery').change(function(){ updateCost(); });
});
$(function(){
$("#amount").keypress( function(e) {
var chr = String.fromCharCode(e.which);
if (".1234567890NOABC".indexOf(chr) < 0)
return false;
});
});
$("#amount").blur(function() {
var input = $(this).val();
if (/^\d*\.?\d{0,2}$/.test(input)) {
var amount = parseFloat(input);
if (amount < 40 || amount > 200) {
$("span.paymentalert").html("Your payment must be between £40 and £200");
} else {
$("span.paymentalert").html("");
}
} else {
$("span.paymentalert").html("Your payment must be a number");
}
});
Try this function like:
function updateCost() {
var amount = parseFloat(document.getElementById("amount").value) || 0.00;
var delivery = document.getElementById("delivery").value;
if(delivery !='select' && delivery)
{
delivery=parseFloat(delivery);
}
else
{
delivery=0.00;
}
var total = amount + delivery;
var fixedrate = total / 100 * 12.2;
var grandtotal = fixedrate + total;
document.getElementById("amountdiv").innerHTML = amount.toFixed(2);
document.getElementById("deliverydiv").innerHTML = delivery.toFixed(2);
document.getElementById("total").innerHTML = total.toFixed(2);
document.getElementById("fixedrate").innerHTML = fixedrate.toFixed(2);
document.getElementById("grandtotal").innerHTML = grandtotal.toFixed(2);
}
Also you have written onchange function 2 times
$(document).ready(function(){
$('#amount').change(function(){ updateCost(); });
$('#delivery').change(function(){ updateCost(); });
});
You can remove it
$(function(){
document.getElementById("amount").onchange =updateCost;
document.getElementById("delivery").onchange = updateCost;
});
Looks like you have missed something
$(function(){
document.getElementById("amount").onchange = // something should be here with statement end
document.getElementById("delivery").onchange = updateCost;
});
see the comment part, you have missed the amount initialization and termination of the statement too.
I hope this will solve the problem with NAN :)