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
Related
Iam working on an application, in the Grand Total field, its showing the sum of all the margin fields totals. But when the page loads its showing NaN in the total field. How can i show the existing total to show up in the Grand Total field?
This is my script.
demo
js
function getIndexedElement(item, index) {
if (item.length) {
if (index < item.length) {
return item[index];
} else {
return false;
}
} else {
if (index === 0) {
return item;
}
}
return false;
}
function isNum(value) {
return 123;
}
function calcTotals() {
var grandTotal = 0;
var margin_total = 0;
var total_inr1 = 0;
var i = 0;
while (getIndexedElement(document.forms['cart'].elements['add_percentage[]'], i)) {
add_percentageObj = getIndexedElement(document.forms['cart'].elements['add_percentage[]'], i);
addon_valueObj = getIndexedElement(document.forms['cart'].elements['addon_value[]'], i);
total_inr_valueObj = getIndexedElement(document.forms['cart'].elements['total_inr[]'], i);
totalObj = getIndexedElement(document.forms['cart'].elements['add_value[]'], i);
priceunitObj = getIndexedElement(document.forms['cart'].elements['price_unit[]'], i);
qtyObj = getIndexedElement(document.forms['cart'].elements['qty[]'], i);
marginObj = getIndexedElement(document.forms['cart'].elements['margin_for[]'], i);
if (isNaN(add_percentageObj.value)) {
add_percentageObj = '';
}
if (isNaN(addon_valueObj.value)) {
addon_valueObj = '';
}
if (add_percentageObj.value != 0) {
totalObj.value = (((total_inr_valueObj.value * 1) * add_percentageObj.value / 100) + total_inr_valueObj.value * 1).toFixed(3);
grandTotal = grandTotal + parseFloat(totalObj.value);
marginObj.value = ((totalObj.value * 1) - (total_inr_valueObj.value * 1)).toFixed(3);
margin_total = ((margin_total * 1) + marginObj.value * 1);
//total_inr1 = total_inr1 + parseFloat(total_inr_valueObj.value);
//c.value=Math.round((b.value/100) *a.value ).toFixed(2);
} else if (addon_valueObj.value != 0) {
totalObj.value = ((addon_valueObj.value * 1) + total_inr_valueObj.value * 1).toFixed(3);
grandTotal = grandTotal + parseFloat(totalObj.value);
marginObj.value = ((totalObj.value * 1) - (total_inr_valueObj.value * 1)).toFixed(3);
margin_total = ((margin_total * 1) + marginObj.value * 1);
//total_inr1 = total_inr1 + parseFloat(total_inr_valueObj.value);
} else {
totalObj.value = ((addon_valueObj.value * 1) + total_inr_valueObj.value * 1).toFixed(3);
grandTotal = grandTotal + parseFloat(totalObj.value);
marginObj.value = ((totalObj.value * 1) - (total_inr_valueObj.value * 1)).toFixed(3);
margin_total = ((margin_total * 1) + marginObj.value * 1);
//total_inr1 = total_inr1 + parseFloat(total_inr_valueObj.value);
}
i++;
}
//document.getElementById('grand_total').value = grandTotal.toFixed(3);
//document.getElementById('margin_total').value = margin_total.toFixed(3);
//document.getElementById('total_inr1').value = total_inr1.toFixed(3);
//document.getElementById('margin_for').value = margin_for;
marginTotal();
return;
}
function marginTotal() {
var x = $('[name="gt[]"]:checked').length;
if (x != 0) return;
var sum = 0;
$('input[name="margin_for[]"]').each(function () {
sum += +this.value;
});
$("#total12").val(sum);
}
$(function () {
$("input[type='checkbox'").on("change", function () {
recalcTotal();
}).change();
function recalcTotal() {
var total12 = 0;
var checkedinput = $("input:checked");
var targetcheckboxes = checkedinput.length ? checkedinput : $("input:checkbox");
targetcheckboxes.each(function () {
total12 += parseFloat($(this).next("input").val(), 10) * 1;
});
$("#total12").val(total12.toFixed(3));
}
});
$(window).load(function () {
$(document).ready(function () {
$("select").on('change', function () {
var dept_number = $(this).val();
var price = $(this).find(':selected').data('price');
var selected = $(this).find('option:selected').text();
if (selected == "INR") {
$(this).closest('table').find('.total1').val($(this).closest('table').find('.total').val());
} else {
$(this).closest('table').find('.total1').val((($(this).closest('table').find('.total').val() * price) / $(this).closest('table').find('.inrvalue').val()).toFixed(3));
}
$(this).closest('table').find('.price_unit').val(($(this).closest('table').find('.total1').val() / $(this).closest('table').find('.qty').val()).toFixed(3));
});
});
}); //]]>
In the fiddle you can see the last field, that is margin field. And extreme down you can see the Grand Total. Page Load its showing NaN..
you simply need to check input value next to checkbox whether its isNaN() or notDEMO There are many bugs like if you enter Text in Total colum you get NaN in textbox beside checkbox as well in Grandtotal since your updating it after change in input you need to validate the textbox on change
targetcheckboxes.each(function () {
var temp=$(this).next("input").val();
if(temp){
total12 += parseFloat(temp, 10) * 1;
}
});
$("#total12").val(total12.toFixed(3));
UPDATED ANSWER
So I was wrong, after some more testing its just that your first 3 readonly checkboxes don't have value=0.000 as an attribute.
As they are text inputs, javascript doesn't automatically assume that an empty input is equal to 0.
just add value=0.000 to the first three checkboxes
INCORRECT OLD ANSWER
In your targetcheckboxes.each() loop, your expression:
total12 += parseFloat($(this).next("input").val(), 10) * 1;
is causing the problem.
next("input") will match any type of input including text inputs. somewhere along the line you are concatenating a string to your total12 variable and hence the final value of total12 can not be parsed to a float.
I think you should use
parseInt(yourvalue);
parseFloat(yourvalue).toFixed(2);
whenever you are calculating something using js
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 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
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 :)
I'm trying to write a function that adds a new "row" that has an optional "cell" to an object. Here is my code:
var init = function() {
var num = 0;
var count = 0;
var SC = {}
var rowAdd = function() {
num = num + 1
var cellstate = false;
var objCount = count + 1
var rowObj = {
number: num,
cell: cellstate
}
return SC.rowObj;
}
var initialize = function() {
rowAdd();
}
initialize();
}
$(document).ready(function() {
init();
addRowBtn.click(function() {
rowAdd();
});
addCellBtn.click(function() {
SC.row1.cell = true;
});
});
This approach rewrites the row everytime i call rowAdd(). In the end I want a single object SC to contain every row, and each row should have a cell property. How can I do this?
Try this. You can just use num for objCount too and no need for cellState variable.
var init = function() {
var num = 0, SC = {}
var rowAdd = function() {
num = num + 1;
SC["row" + num] = {
number: num,
cell: false
}
return SC;
}
}
How about making SC an array and pushing the new row onto the array:
var SC = [];
var rowAdd = function() {
num = num + 1
var cellstate = false;
var objCount = count + 1;
var rowObj = "row" + objCount;
var rowObj = {
number: num,
cell: cellstate
}
return SC.push(rowObj);
}
You'll want to have an array object on SC to hold your rows.
var SC = { rows: [] };
And then add to it
SC.rows.push(rowObj);
To access
SC.rows[index]