apply discounts to values in json javascript - javascript

I have an app with 3 items to purchase (3 books: wiz[0], lorax[1], and democrat[2]). These 3 books all cost $24.95, but two books cost $44.90(-$5 Off total), and three books cost $59.85(-$10 Off total). But the 4th or + book should be discounted to $19.95 with no further discounts. I am stuck on my third function "__totalWithDiscounts()". Does anyone have any idea how to do this? I feel like its super simple but I don't know what to do.
var cartJSON = [{'id':'wiz','count':0},
{'id':'gorax','count':0},
{'id':'democrat','count':0}]
function __updateTheTotal(item,quantity){
// find book being updated and change the count to the passed quantity
for (var i=0; i<cartJSON.length; i++) {
if (cartJSON[i].id == item) {
cartJSON[i].count = quantity;
break;
}
}
__totalWithDiscounts();
}
function __totalWithDiscounts(){
// this function will get the new json data generated by the inputs and apply discounts based on the amount
var discount_offTwoBooks = Number(5);
var discount_offThreeBooks = Number(10);
var priceOfEachBook_default = Number(24.95);
var priceOfEachBook_afterCountIs4 = Number(19.95);
var totalOf_wiz = Number(cartJSON[0].count);
var totalOf_gorax = Number(cartJSON[1].count);
var totalOf_democrat = Number(cartJSON[2].count);
var totalOf_all = +totalOf_wiz +totalOf_gorax +totalOf_democrat;
console.log('total books: '+totalOf_all);
}

I'd do this. Haven't tested this but pretty sure it'd work:
function __totalWithDiscounts(){
// this function will get the new json data generated by the inputs and apply discounts based on the amount
var discount_offTwoBooks = Number(5);
var discount_offThreeBooks = Number(10);
var priceOfEachBook_default = Number(24.95);
var priceOfEachBook_afterCountIs4 = Number(19.95);
var totalOf_wiz = Number(cartJSON[0].count);
var totalOf_gorax = Number(cartJSON[1].count);
var totalOf_democrat = Number(cartJSON[2].count);
var totalOf_all = 0+totalOf_wiz +totalOf_gorax +totalOf_democrat;
console.log('total books: '+totalOf_all);
var priceOfAll = 0;
if(totalOf_all >=4 ) priceOfAll = totalOf_all * priceOfEachBook_afterCountIs4;
else if(totalOf_all == 3) priceOfAll = priceOfEachBook_default * 3 - discount_offThreeBooks;
else if(totalOf_all == 2) priceOfAll = priceOfEachBook_default * 2 - discount_offTwoBooks;
else priceOfAll = priceOfEachBook_default * 1;
}
A bit of advice: use better variable names. And this was a simple logical construct of branching. Not that difficult to grasp: https://en.wikipedia.org/wiki/Conditional_(computer_programming)

Here's a jsfiddle with a solution: https://jsfiddle.net/6p1n1tta/3/
var totalOf_all = totalOf_wiz + totalOf_gorax + totalOf_democrat;
var discount = 0;
switch (totalOf_all) {
case 1: {
discount = 0;
break;
}
case 2: {
discount = discount_offTwoBooks;
break;
}
case 3: {
discount = discount_offThreeBooks;
break;
}
default: {
discount = priceOfEachBook_afterCountIs4;
break;
}
}
var totalPrice = (totalOf_all * priceOfEachBook_default) - discount;
console.log('total books: ' + totalOf_all + '\n' + 'total price: ' + totalPrice);
Also, in your __updateTheTotal function, it should be cartJSON[i].count += quantity;. The count won't properly update until you make that change.

Related

Invoking else statement every time

this is My code for adding a order details to the database. I want to check whether Stock Amount is higher or lower than Order Amount.So i put if statements on this. But every time it Invoke else statement. What is the wrong with this code
It Always Invoke Else Statement
function OrderAdd() {
var INameO = $("#INanme").text();
var IpriceO = $("#IPrice").text();
var IquantityO = $("#OQuntity").val();// order Amount
var Oquantity = $('#IQuantity').text(); //stock Amount
var Total = $("#IPrice").text() * $("#OQuntity").val();
if(Oquantity>IquantityO) {
addOrder(INameO, IpriceO, IquantityO, Total);
viewAllOrders();
gettotal();
clearItemArea();
console.log(IquantityO);
console.log(Oquantity);
}
else {alert("Amount exceeded")
}
}
function gettotal() {
var temptotal = 0;
var temp = getAllOrders();
for (var i = 0; i < temp.length; i++) {
var Total = temp[i].getOtotal();
temptotal = temptotal+Total;
$('#totalP').text(temptotal);
}
}
There is a one error. I didn't change values to the INT type. That's Why else Statement Invoking Every time. You can understand Better after watching this code.
function OrderAdd() {
var INameO = $("#INanme").text();
var IpriceO = parseInt( $("#IPrice").text());
var Oquantity =parseInt( $('#IQuantity').text()); //stock Amount
var IquantityO = parseInt($("#OQuntity").val());// order Amount
var Total = $("#IPrice").text() * $("#OQuntity").val();
//findduplicates(INameO);
if (Oquantity>IquantityO){
addOrder(INameO, IpriceO, IquantityO, Total);
viewAllOrders();
gettotal();
clearItemArea();
}
else{alert("Amount exceeded!")
}
}

Keep function from affecting certain parts of an array

I am creating a program which will sort people's names into different tables(table1, table2, table3, table4) which are represented by arrays and it will add any preferences that people would like to sit by into the same table as them. I have a function, check(), which makes sure there are no duplicate names and that the tables' length does not exceed 6. The problem is the check() function moves the preferences out of the table they need to be in. Is there any way to keep this from happening? Thank you.
JavaScript:
$(document).ready(function () {
var table1 = [];
var table2 = [];
var table3 = [];
var table4 = [];
var names = [];
var pref = [];
function seat() {
for (var i = 0; i < names.length; i++) {
if (pref != "") {
if (pref == names[i]) {
var who = names[i];
function prandomize(min, max) {
var pr = Math.floor(Math.random() * (max - min + 1)) + min;
if (pr == 1) {
table1.push(names[i]);
table1.push(who);
} else if (pr == 2) {
table2.push(names[i]);
table2.push(who);
} else if (pr == 3) {
table3.push(names[i]);
table3.push(who);
} else if (pr == 4) {
table4.push(names[i]);
table4.push(who);
} else {
return "Error: Contact Source Code Author!!";
}
}
}
}
function randomize(min, max) {
var r = Math.floor(Math.random() * (max - min + 1)) + min;
if (r == 1) {
table1.push(names[i]);
} else if (r == 2) {
table2.push(names[i]);
} else if (r == 3) {
table3.push(names[i]);
} else if (r == 4) {
table4.push(names[i]);
} else {
return "Error: Contact Source Code Author!!";
}
}
randomize(1, 4);
};
console.log(table1);
console.log(table2);
console.log(table3);
console.log(table4);
console.log("first call");
};
var htable1 = document.getElementById('t1');
var htable11 = document.getElementById('t11');
var htable111 = document.getElementById('t111');
var htable1111 = document.getElementById('t1111');
var htable11111 = document.getElementById('t11111');
var htable111111 = document.getElementById('t111111');
var htable2 = document.getElementById('t2');
var htable22 = document.getElementById('t22');
var htable222 = document.getElementById('t222');
var htable2222 = document.getElementById('t2222');
var htable22222 = document.getElementById('t22222');
var htable222222 = document.getElementById('t222222');
var htable3 = document.getElementById('t3');
var htable33 = document.getElementById('t33');
var htable333 = document.getElementById('t333');
var htable3333 = document.getElementById('t3333');
var htable33333 = document.getElementById('t33333');
var htable333333 = document.getElementById('t333333');
var htable4 = document.getElementById('t4');
var htable44 = document.getElementById('t44');
var htable444 = document.getElementById('t444');
var htable4444 = document.getElementById('t4444');
var htable44444 = document.getElementById('t44444');
var htable444444 = document.getElementById('t444444');
function check() {
var stable1 = table1.slice().sort();
for (var i = 0; i < table1.length - 1; i++) {
if (stable1[i + 1] == stable1[i]) {
table1.splice(i, 1);
console.log("removed");
}
}
if (table1.length > 6) {
while (table1.length > 6) {
var lastvalue = table1.pop();
table2.push(lastvalue);
console.log("moved to table2");
}
}
if (table2.length > 6) {
while (table2.length > 6) {
var lastvalue2 = table2.pop();
table3.push(lastvalue2);
console.log("moved to table3");
}
}
if (table3.length > 6) {
while (table3.length > 6) {
var lastvalue3 = table3.pop();
table4.push(lastvalue3);
console.log("moved to table4");
}
}
if (table4.length > 6) {
while (table4.length > 6) {
var lastvalue4 = table4.pop();
table1.push(lastvalue4);
console.log("moved to table1");
}
}
}
function changeHTML() {
htable1.innerHTML = table1[0];
htable11.innerHTML = table1[1];
htable111.innerHTML = table1[2];
htable1111.innerHTML = table1[3];
htable11111.innerHTML = table1[4];
htable111111.innerHTML = table1[5];
htable2.innerHTML = table2[0];
htable22.innerHTML = table2[1];
htable222.innerHTML = table2[2];
htable2222.innerHTML = table2[3];
htable22222.innerHTML = table2[4];
htable222222.innerHTML = table2[5];
htable3.innerHTML = table3[0];
htable33.innerHTML = table3[1];
htable333.innerHTML = table3[2];
htable3333.innerHTML = table3[3];
htable33333.innerHTML = table3[4];
htable333333.innerHTML = table3[5];
htable4.innerHTML = table4[0];
htable44.innerHTML = table4[1];
htable444.innerHTML = table4[2];
htable4444.innerHTML = table4[3];
htable44444.innerHTML = table4[4];
htable444444.innerHTML = table4[5];
}
function namesdefine() {
names.push(document.getElementById('nameone').value);
names.push(document.getElementById('nametwo').value);
names.push(document.getElementById('namethree').value);
names.push(document.getElementById('namefour').value);
names.push(document.getElementById('namefive').value);
names.push(document.getElementById('namesix').value);
names.push(document.getElementById('nameseven').value);
names.push(document.getElementById('nameeight').value);
names.push(document.getElementById('namenine').value);
names.push(document.getElementById('nameten').value);
names.push(document.getElementById('nameeleven').value);
names.push(document.getElementById('nametwelve').value);
names.push(document.getElementById('namethirteen').value);
names.push(document.getElementById('namefourteen').value);
names.push(document.getElementById('namefifthteen').value);
names.push(document.getElementById('namesixteen').value);
names.push(document.getElementById('nameseventeen').value);
names.push(document.getElementById('nameeighteen').value);
names.push(document.getElementById('namenineteen').value);
names.push(document.getElementById('nametwenty').value);
names.push(document.getElementById('nametwentyone').value);
names.push(document.getElementById('nametwentytwo').value);
names.push(document.getElementById('nametwentythree').value);
names.push(document.getElementById('nametwentyfour').value);
console.log(names);
var testvar = document.getElementById('nameone').value;
console.log(testvar);
console.log("Look here please");
}
function prefsdefine() {
pref.push(document.getElementById('prefone').value);
pref.push(document.getElementById('preftwo').value);
pref.push(document.getElementById('prefthree').value);
pref.push(document.getElementById('preffour').value);
pref.push(document.getElementById('preffive').value);
pref.push(document.getElementById('prefsix').value);
pref.push(document.getElementById('prefseven').value);
pref.push(document.getElementById('prefeight').value);
pref.push(document.getElementById('prefnine').value);
pref.push(document.getElementById('preften').value);
pref.push(document.getElementById('prefeleven').value);
pref.push(document.getElementById('preftwelve').value);
pref.push(document.getElementById('prefthirteen').value);
pref.push(document.getElementById('preffourteen').value);
pref.push(document.getElementById('preffifthteen').value);
pref.push(document.getElementById('prefsixteen').value);
pref.push(document.getElementById('prefseventeen').value);
pref.push(document.getElementById('prefeightteen').value);
pref.push(document.getElementById('prefnineteen').value);
pref.push(document.getElementById('preftwenty').value);
pref.push(document.getElementById('preftwentyone').value);
pref.push(document.getElementById('preftwentytwo').value);
pref.push(document.getElementById('preftwentythree').value);
pref.push(document.getElementById('preftwentyfour').value);
}
document.getElementById('sbm').addEventListener('click', function (e) {
e.preventDefault();
namesdefine();
prefsdefine();
seat();
check();
check();
check();
changeHTML();
});
console.log(table1);
console.log(table2);
console.log(table3);
console.log(table4);
console.log("second call");
console.log(pref);
});
I would suggest that you first focus on the data structures that you are using before you try to go too much further. The preferences handling is trickier than it seems at first because you could have person1 who wants to sit with person2, but person2 wants to sit beside person6. This creates a chain of preferences that is not trivial to handle.
Before you try to tackle that, I would suggest you try creating a single data structure (rather than four tables). This data structure might be an array of size 24 holding objects that looks something like this:
{ name: 'xxx', preference: 'yyy', table: n }
If you are not comfortable with objects, or arrays of objects, I would suggest that you focus your efforts on learning them since they are absolutely essential in JavaScript. Arrays are handy but, in practice, they tend to be for very simple lists or as containers to hold objects.
I could provide you code that will do what you want but I don't think that will help you in your learning curve. Take a stab at applying a different data structure and if you get stuck there, maybe post a new question on SO. There are plenty of people that want to help but you will need to do your homework to get assistance along the way.

javascript: clean way of converting currencies from an array

Folks!
Currently i have written this below code, which converts one currencies into another , but the problem is i am defining each & every currencies one by one in switch block,
If i have 100 currencies to convert then i have to write 100 switch cases
Is there any i can make this below code dynamic and short?
var currencies = {};
$(document).ready(function(){
yahoo_getdata();
});
function yahoo_getdata() {
var a = new Date();
var b = "http://someAPIurl.com/webservice/v1/symbols/allcurrencies/quote?format=json&random=" + a.getTime() + "&callback=?";
$.getJSON(b, function (e) {
if (e) {
var i, l, r, c;
r = e.list.resources;
for (i = 0, l = r.length; i < l; i += 1) {
c = r[i].resource.fields;
//console.log(c.name, c.price);
switch (c.name) {
case "USD/EUR":
currencies.EUR = c.price;
console.log('USD/EUR = ' + c.price);
break;
case "USD/USD":
currencies.USD = c.price;
console.log('USD/USD = ' + c.price);
break;
case "USD/JPY":
currencies.JPY = c.price;
console.log('USD/JPY = ' + c.price);
break;
case "USD/INR":
currencies.INR = c.price;
console.log('USD/INR = ' + c.price);
break;
}
}
console.log(currencies);
//console.log(e);
//var d = {};
}
});
}
$("#amount1").keyup(function() {
var
usd,
amount1 = $('#amount1').val(),
currency1 = $("#currency1").val(),
currency2 = $("#currency2").val();
// normalize to USD
usd = amount1 / currencies[currency1];
// convert to target currency
$('#amount2').val(usd * currencies[currency2]);
});
Use an object that maps the currency name to the object property name:
var currency_map = {
'USD/EUR': 'EUR',
'USD/USD': 'USD',
'USD/JPY': 'JPY',
...
};
Then:
for (var i = 0, l = r.length; i < l; i++) {
c = r[i].resource.fields;
currencies[currency_map[c.name] || c.name] = c.price;
console.log(c.name + ' = ' + c.price);
}
FIDDLE

jQuery calculation on form txt fields

looking for a bit of help with my jQuery, (i know its not the best)
Currently have a form, split into 2 sides,
on the left I have a list of assests on the right is the liabilities
somewhat of a balance sheet for account, see the image below
the jquery in use just now, is a bit of a mess.. (sorry)
this code will calculate the field totals on each keyup request, which seems to work ok,
jQuery('#ass_cash, #ass_liquid, #ass_lifeinsu, #ass_covvalue, #ass_la1, #ass_la2, #ass_la3, #ass_realestate, #ass_auto1total, #ass_auto2total, #lib_mortgage, #lib_bankloan1, #lib_bankloan2, #lib_loansinsucomp, #lib_loanscreditunion, #lib_creditcards, #lib_od1, #lib_od2, #lib_od3, #lib_rent, #lib_mortgagemthpmt, #lib_bankloan1mthpmt, #lib_bankloan2mthpmt, #lib_loansinsucompmthpmt, #lib_loanscreditunionmthpmt, #lib_creditcardsmthpmt, #lib_od1mthpmt, #lib_od2mthpmt, #lib_od3mthpmt, #lib_rentmthpmt').keyup( function(){
// ASSESTS
var ass_cash = jQuery("#ass_cash").val();
var ass_liquid = jQuery("#ass_liquid").val();
var ass_lifeinsu = jQuery("#ass_lifeinsu").val();
var ass_covvalue = jQuery("#ass_covvalue").val();
var ass_la1 = jQuery("#ass_la1").val();
var ass_la2 = jQuery("#ass_la2").val();
var ass_la3 = jQuery("#ass_la3").val();
var ass_realestate = jQuery("#ass_realestate").val();
var ass_auto1total = jQuery("#ass_auto1total").val();
var ass_auto2total = jQuery("#ass_auto2total").val();
var ass_total = jQuery("#ass_total").val();
if(ass_cash==''){ ass_cash = 0; }
if(ass_liquid==''){ ass_liquid = 0; }
if(ass_lifeinsu==''){ ass_lifeinsu = 0; }
if(ass_covvalue==''){ ass_covvalue = 0; }
if(ass_la1==''){ ass_la1 = 0; }
if(ass_la2==''){ ass_la2 = 0; }
if(ass_la3==''){ ass_la3 = 0; }
if(ass_realestate==''){ ass_realestate = 0; }
if(ass_auto1total==''){ ass_auto1total = 0; }
if(ass_auto2total==''){ ass_auto2total = 0; }
var asssubtotal = parseInt(ass_cash) + parseInt(ass_liquid) + parseInt(ass_lifeinsu) + parseInt(ass_covvalue);
asssubtotal = asssubtotal + parseInt(ass_la1) + parseInt(ass_la2) + parseInt(ass_la3) + parseInt(ass_realestate);
asssubtotal = asssubtotal + parseInt(ass_auto1total) + parseInt(ass_auto2total);
var asstotal = jQuery('#ass_total');
asstotal.val(asssubtotal);
// LIABILITIES
var lib_mortgage = jQuery("#lib_mortgage").val();
var lib_bankloan1 = jQuery("#lib_bankloan1").val();
var lib_bankloan2 = jQuery("#lib_bankloan2").val();
var lib_loansinsucomp = jQuery("#lib_loansinsucomp").val();
var lib_loanscreditunion = jQuery("#lib_loanscreditunion").val();
var lib_creditcards = jQuery("#lib_creditcards").val();
var lib_od1 = jQuery("#lib_od1").val();
var lib_od2 = jQuery("#lib_od2").val();
var lib_od3 = jQuery("#lib_od3").val();
var lib_rent = jQuery("#lib_rent").val();
if(lib_mortgage==''){ lib_mortgage = 0; }
if(lib_bankloan1==''){ lib_bankloan1 = 0; }
if(lib_bankloan2==''){ lib_bankloan2 = 0; }
if(lib_loansinsucomp==''){ lib_loansinsucomp = 0; }
if(lib_loanscreditunion==''){ lib_loanscreditunion = 0; }
if(lib_creditcards==''){ lib_creditcards = 0; }
if(lib_od1==''){ lib_od1 = 0; }
if(lib_od2==''){ lib_od2 = 0; }
if(lib_od3==''){ lib_od3 = 0; }
if(lib_rent==''){ lib_rent = 0; }
var libsubtotal = parseInt(lib_mortgage) + parseInt(lib_bankloan1) + parseInt(lib_bankloan2) + parseInt(lib_loansinsucomp);
libsubtotal = libsubtotal + parseInt(lib_loanscreditunion) + parseInt(lib_creditcards) + parseInt(lib_od1) + parseInt(lib_od2);
libsubtotal = libsubtotal + parseInt(lib_od3) + parseInt(lib_rent);
var lib_subtotal = jQuery('#lib_subtotal'); lib_subtotal.val(libsubtotal);
// MONTHLY PAYMENTS
var lib_mortgagemthpmt = jQuery("#lib_mortgagemthpmt").val();
var lib_bankloan1mthpmt = jQuery("#lib_bankloan1mthpmt").val();
var lib_bankloan2mthpmt = jQuery("#lib_bankloan2mthpmt").val();
var lib_loansinsucompmthpmt = jQuery("#lib_loansinsucompmthpmt").val();
var lib_loanscreditunionmthpmt = jQuery("#lib_loanscreditunionmthpmt").val();
var lib_creditcardsmthpmt = jQuery("#lib_creditcardsmthpmt").val();
var lib_od1mthpmt = jQuery("#lib_od1mthpmt").val();
var lib_od2mthpmt = jQuery("#lib_od2mthpmt").val();
var lib_od3mthpmt = jQuery("#lib_od3mthpmt").val();
var lib_rentmthpmt = jQuery("#lib_rentmthpmt").val();
if(lib_mortgagemthpmt==''){ lib_mortgagemthpmt = 0; }
if(lib_bankloan1mthpmt==''){ lib_bankloan1mthpmt = 0; }
if(lib_bankloan2mthpmt==''){ lib_bankloan2mthpmt = 0; }
if(lib_loansinsucompmthpmt==''){ lib_loansinsucompmthpmt = 0; }
if(lib_loanscreditunionmthpmt==''){ lib_loanscreditunionmthpmt = 0; }
if(lib_creditcardsmthpmt==''){ lib_creditcardsmthpmt = 0; }
if(lib_od1mthpmt==''){ lib_od1mthpmt = 0; }
if(lib_od2mthpmt==''){ lib_od2mthpmt = 0; }
if(lib_od3mthpmt==''){ lib_od3mthpmt = 0; }
if(lib_rentmthpmt==''){ lib_rentmthpmt = 0; }
var lib_surplus = jQuery('#lib_surplus');
if(lib_surplus==''){ lib_surplus = 0; }
var subtotal = parseInt(lib_mortgagemthpmt) + parseInt(lib_bankloan1mthpmt) + parseInt(lib_bankloan2mthpmt) + parseInt(lib_loansinsucompmthpmt);
subtotal = subtotal + parseInt(lib_loanscreditunionmthpmt) + parseInt(lib_creditcardsmthpmt) + parseInt(lib_od1mthpmt) + parseInt(lib_od2mthpmt);
subtotal = subtotal + parseInt(lib_od3mthpmt) + parseInt(lib_rentmthpmt);
var totalmthpmt = jQuery('#lib_totalmthpmt');
totalmthpmt.val(subtotal);
var assets_total = jQuery('#ass_total').val();
var lib_subtotal = jQuery('#lib_subtotal').val();
var lib_surplus = jQuery('#lib_surplus');
if(assets_total==''){ assets_total = 0; }
if(lib_subtotal==''){ lib_subtotal = 0; }
if(lib_surplus==''){ lib_surplus = 0; }
var surplus = assets_total - lib_subtotal;
lib_surplus.val(surplus);
// THIS IS THE PART THAT ISNT WORKING
//surplus/deficit
//var lib_total = jQuery('#lib_total').val();
//if(lib_total==''){ lib_total = 0; }
//var lib_totalmthpmt = jQuery('#lib_totalmthpmt').val();
//if(lib_totalmthpmt==''){ lib_totalmthpmt = 0; }
//var surplustotal = lib_total - lib_totalmthpmt;
//jQuery('#mthsurplus').val(surplustotal);
});
you can see the section which is causing issues above, its the calculation between the subtotal (minus) Surplus to generate the total,
each field for asset has a class .asset
each libability has class .liability
each monthly payment field has class .liabilitymth
Ive tried doing the jQuery('.asset').each(function() and trying to generate the total in the asset field, same for the other 2, sections,
the greyed out boxes are "readonly", were the calculations should appear.
ASSETS: The total on the left side of the page will be the total assets.
LIABILITIES: The 'Subtotal' will reflect the sum of the Liability column.
SURPLUS: This will represent the difference (Negative'-' OR Positive'+'), between the Assets & Liabilities-Balance column.
TOTAL(Right Side): This is to create a 'Balance Sheet'effect, so when you look at it, the calculation should reflect the same figure as the 'Total' over on the Asset side (Left side).
MONTHLY-SURPLUS/ DEFICIT: This should reflect the net difference in Total Income Revenue, either negative OR positive (Figure found From the Employment Tab), when compared with the total of the 'Monthly Payment' column.
this is where my jQuery falls flat on its face, there has to be an easier way to calculate the field totals, anyone shed any light on this, or have a much better use of code, rather than wrapping it all under a very large keyup request :)
This can give you the head start:
var totalAss = 0;
jQuery('.asset').each(function(){
var value = parseFloat(this.value);
if (value)
totalAss += value;
});
jQuery('#ass_total').val(totalAss);
There is indeed some easy way. Do things like that
on all classes means .assets , .liability and .liabilitymth do this on document.ready
$(function()
{
$('.assets , .liability ,.liabilitymth').each(function()
{
var value = $(this).val();
if(value == "")
{
$(this).val('000.00');
}
});
});
And now
var total_assets = 0;
$('.assets').keyup(function(){
var number = $(this).val();
total_assets += parseInt(number);
});
After that
$('#total_assets').val(total_assets);
If you do the calculation in the keyup or any other key events, then there will be a problem of keeping track of the old data that was entered. For ex., at an instant you had typed 50 and then you made it to 500 and then you made it to say 30. Then, the keyevent will not be able to figure out the difference between both the old and new data. You will have to write some logic to figure out the old and the new updated data and then depending on that you will have to update the final value. It is better if you can code something like this...
http://jsfiddle.net/AvSEG/

Javascript, trying to get conversion average

I have a script that is setting conversion rates depending on input boxes (works fine), however I now want to get an average of these rates.
My Code is
var avg1 = $('#conversion1').text();
var avg2 = $('#conversion2').text();
var avg3 = $('#conversion3').text();
var avg4 = $('#conversion4').text();
var avg5 = $('#conversion5').text();
var avg6 = $('#conversion6').text();
var sumavg = (avg1 + avg2 + avg3 + avg4 + avg5 + avg6) / 6;
sumavg = Math.round(sumavg*Math.pow(10,2))/Math.pow(10,2);
$('#conversion7').html(sumavg);
The id conversion1,2 etc have a number from 0-100 (the conversion rate). However whenever I run this script I get all sorts of crazy numbers for the average (sumavg or id conversion7). I do not know why! I should also note that this bit of code is inside of the function doing the conversion for each day which works fine.
See below for entire snippet:
// Conversion Rate
$.fn.sumConv = function(customers) {
var sum = 0;
var val = 0
this.each(function() {
if ( $(this).is(':input') ) {
val = $(this).val();
} else {
val = $(this).text();
}
customersval = $(customers).val();
sum = (customersval/val) * 100;
//sum += parseFloat( ('0' + val).replace(/[^0-9-\.]/g, ''), 10 );
sum = Math.round(sum*Math.pow(10,2))/Math.pow(10,2);
if(sum=="Infinity" || sum=="NaN") sum=0;
});
// do average
var avg1 = $('#conversion1').text();
var avg2 = $('#conversion2').text();
var avg3 = $('#conversion3').text();
var avg4 = $('#conversion4').text();
var avg5 = $('#conversion5').text();
var avg6 = $('#conversion6').text();
var sumavg = (avg1 + avg2 + avg3 + avg4 + avg5 + avg6) / 6;
sumavg = Math.round(sumavg*Math.pow(10,2))/Math.pow(10,2);
$('#conversion7').html(sumavg);
return sum;
};
$('input#foot1').bind('keyup', function() {
$('#conversion1').html( $('input#foot1').sumConv('input#customers1') );
});
$('input#customers1').bind('keyup', function() {
$('#conversion1').html( $('input#foot1').sumConv('input#customers1') );
});
$('input#foot2').bind('keyup', function() {
$('#conversion2').html( $('input#foot2').sumConv('input#customers2') );
});
$('input#customers2').bind('keyup', function() {
$('#conversion2').html( $('input#foot2').sumConv('input#customers2') );
});
$('input#foot3').bind('keyup', function() {
$('#conversion3').html( $('input#foot3').sumConv('input#customers3') );
});
$('input#customers3').bind('keyup', function() {
$('#conversion3').html( $('input#foot3').sumConv('input#customers3') );
});
$('input#foot4').bind('keyup', function() {
$('#conversion4').html( $('input#foot4').sumConv('input#customers4') );
});
$('input#customers4').bind('keyup', function() {
$('#conversion4').html( $('input#foot4').sumConv('input#customers4') );
});
$('input#foot5').bind('keyup', function() {
$('#conversion5').html( $('input#foot5').sumConv('input#customers5') );
});
$('input#customers5').bind('keyup', function() {
$('#conversion5').html( $('input#foot5').sumConv('input#customers5') );
});
$('input#foot6').bind('keyup', function() {
$('#conversion6').html( $('input#foot6').sumConv('input#customers6') );
});
$('input#customers6').bind('keyup', function() {
$('#conversion6').html( $('input#foot6').sumConv('input#customers6') );
});
I suppose you have to apply parseFloat to your data. text method returns string, not number. Take a look at the simple example:
var avg1 = "1";
var avg2 = "1";
var avg3 = "1";
var avg4 = "1";
var avg5 = "1";
var avg6 = "1";
var sumavg = (avg1 + avg2 + avg3 + avg4 + avg5 + avg6) / 6;
sumavg will be 18518.5 and not 1.
Wrap all avg data with parseFloat:
var avgN = parseFloat($('#conversionN').text());
You're repeating a lot of code, so I advise employing a DRY technique to minimise that -- e.g. make a bindKeyUp function...
Anyway, you need numbers. .text() returns strings. E.g. "99" + "77" === "9977". This is where your crazy numbers might be coming from. Try this:
var avg1 = ~~$('#conversion1').text();
var avg2 = ~~$('#conversion2').text();
// repeat
~~ just converts its operand to a number (and floors it towards 0). More info.
Or, to make it clearer, use parseFloat:
var avg1 = parseFloat($('#conversion1').text());
var avg2 = parseFloat($('#conversion2').text());
// repeat

Categories