Javascript cost calculator wont work as supposed - javascript

Hello I am new to Js and I want to make a cost calculation function. So far it works but Its not what I want to have. Here is how it looks
<script>
function finalCost(){
var roomType = document.getElementById("roomtype").value;
var roomNum = document.getElementById("rooms").value;
var personNum = document.getElementById("atoma").value;
var childNum = document.getElementById("paidia").value;
var resFacilities =
document.getElementById("meal").value;
var atoma = childNum + personNum;
var roomty = (parseInt(roomType));
var total = +roomty + +atoma + +((resFacilities));
document.getElementById("result").innerHTML = total;
}
</script>
However, I want to have something like that: ( It wont work I know)
<script>
function finalCost(){
var roomType = document.getElementById("roomtype").value;
var roomNum = document.getElementById("rooms").value;
var personNum = document.getElementById("atoma").value;
var childNum = document.getElementById("paidia").value;
var resFacilities =
document.getElementById("meal").value;
var atoma = childNum + personNum;
var roomty = (parseInt(roomType));
var total = +roomty*roomNum + +atoma + +((resFacilities)*atoma);
document.getElementById("result").innerHTML = total;
}
</script>
If I enter the above code the cost wont work at all If i enter it without the *roomNum the cost will work without the meal included.
Please give me some advice as I am really frustrated by this issue.

If i understand this correctly because I'm unsure of the exact calculation you are trying to compute:
// Total calculated as room type times number of rooms times number of people.
// Adding meal costs per person.
var total = roomty*roomNum*atoma +(resFacilities*atoma);

Your code is working fine please see console output
Of this is not what you looking for. Put your html, javascript somewhere at one place. Where you code can be executed.

Related

Javascript count two variables goes wrong

I am busy with making a kind of invoice system, where the user can make invoices very easily. Now I am at the point where I have to count up, per product, three different variables/items, but instead of counting them up, my javascript code puts it like text (with the + operator).
Example:
selectmenu 1 = option 0 (where VAT = 8.50 euro's)
selectmenu 2 = option 1 (where VAT = 12.76 euro's)
Now the output has to be (8.50+12.76)= 21.26
The output in my situation is = 8.5012.76
My (partial) javascript code:
$("select#product").on("change", function (e) {
var $row = $(e.target).closest('.productitem');
var selVal = $row.find('#product').val();
var totalvat;
var currentVat = $('#totalvat').val();
var NLhoog = 1.21;
var price0EXC = 40.49;
var price0INC = (price0EXC * NLhoog).toFixed(2);
var price0VAT = (price0INC - price0EXC).toFixed(2);
var price1EXC = 60.74;
var price1INC = (price1EXC * NLhoog).toFixed(2);
var price1VAT = (price1INC - price1EXC).toFixed(2);
if (selVal === "0") {
$row.find("input#vat").val(price0VAT);
$row.find("input#priceEXC").val(price0EXC);
$row.find("input#priceINC").val(price0INC);
totalvat = (currentVat + price0VAT);
$('input#totalvat').val(totalvat);
} else if (selVal === "1") {
$row.find("input#vat").val(price1VAT);
$row.find("input#priceEXC").val(price1EXC);
$row.find("input#priceINC").val(price1INC);
totalvat = currentVat+price1VAT;
$('input#totalvat').val(totalvat);
}
});
I have let the unimportant part of the code away.
If you know what I am doing wrong, please let me know :)
Think this may help?
var currentVat = parseFloat($('#totalvat').val());
You are using var currentVat = $('#totalvat').val(); to get the value from an input I assume? This is a string which will need to be parsed at some to a relevant datatype. When + is used with a string the compiler performs concatenation.
Try something like:
var currentVat = parseFloat($('#totalvat').val());
Or do it later on with:
parseFloat(currentVat);
As you're using numbers as currency I'd consider adding the suffix .ToFixed(2) at the end, and maybe some other formatting

Javascript - NaN

I am currently trying to do a small calculation to find the Markup of a product. How ever I am getting a 'NaN' error in my console. Obviously I know this means Not a Number but I can't figure out how to fix the error.
function calculateSuggestedCost() {
var suggestedCost = 0;
var idealGP = $('#bc_inventorybundle_dish_ideal_gp').val;
var cost = $('#bc_inventorybundle_dish_cost').val;
suggestedCost = parseFloat(cost /(1 - idealGP));
$('#bc_inventorybundle_dish_suggested_price').val(suggestedCost);
}
// =Cost/(1-Margin Percentage)
I've tried using parseFloat but I'm guessing the way I've used it isn't quite right.
Thank's for all the quick replies. Modification of Joe Frambach's answer just to show my final working solution for anyone else looking.
function calculateSuggestedCost() {
var suggestedCost = 0;
var idealGP = parseFloat($('#bc_inventorybundle_dish_ideal_gp').val());
var cost = parseFloat($('#bc_inventorybundle_dish_cost').val());
suggestedCost = Math.round(cost /(1 - (idealGP/100)));
$('#bc_inventorybundle_dish_suggested_price').val(suggestedCost);
calculateActualGP();
}
jQuery val is a function. You need () to call a function:
var idealGP = $('#bc_inventorybundle_dish_ideal_gp').val();
var cost = $('#bc_inventorybundle_dish_cost').val();
Also, when reading numbers from an external source, it is best to convert to numbers and do validation immediately, not during your calculation:
var idealGP = parseFloat($('#bc_inventorybundle_dish_ideal_gp').val());
var cost = parseFloat($('#bc_inventorybundle_dish_cost').val());
suggestedCost = cost /(1.0 - idealGP); // now you can assume that everything is numbers.
when your are trying to get the value from some it or so use .val(). not val
var idealGP = $('#bc_inventorybundle_dish_ideal_gp').val();

Save and print list with array

I need help print and save element in an array in javascript. I know that I have to create an array, and then use a for-loop to save and print it, but i don't know how. What i want to do i so make a simple currency converter, use a for-loop with an array to save the converted input and display it. Here is my code:
JAVASCRIPT
var input = document.querySelector("#input");
var convert = document.querySelector("#convert");
var dollar = 0.51;
var euro = 0.11;
omvandla.onclick = function (){
if(isNaN(input.value)){
alert ("Use numbers");
}
else{
console.log(("Dollar:" + input.value*dollar) + ("Euro:" + input.value*euro));
}
};
HTML
<p>
<form>
<label>Kronor: <input type="text" id="kronor"/></label>
<br><input type="submit" id="convert" value="Omvandla"/>
</from>
</p>
How can I append the converted value after the submit button?
If you want to display one Conversion Result after another, you could do this like this:
var input = document.querySelector("#kronor");
var convert = document.querySelector("#convert");
var dollar = 0.51;
var euro = 0.11;
var conversionArray = [];
convert.onclick = function (){
if(isNaN(input.value)){
alert ("Use numbers");
}
else{
var dollarResult = input.value*dollar;
var euroResult = input.value*euro;
var newArrayEl = {
dollar: dollarResult,
euro: euroResult
};
conversionArray.push(newArrayEl);
console.log(conversionArray);
document.getElementById("convertedValue").innerHTML = "Dollar: " + dollarResult + " Euro: " + euroResult + "<br>" + document.getElementById("convertedValue").innerHTML;
}
};
Then you can access single values of the conversion by e.g. conversionArray[indexOfElement].dollar
This way you don't need an array to store the values. If you really need thos wvalues again, let me know, and im showing you how to store the array.
Here is a Fiddle, that shows how it works.
In javascript the way you add elements to an array is the push function
var myArray = [];
myArray.push(15);
Then to loop through the elements you can do something like this
for(var elem in myArray){
//Do something with elem
}
From your problem description it is hard to figure out what you are trying to do with your code. Hopefully this will help with array manipulation
You can add an element to the end of an array by using the array.push() function. I your example you would do something like:
array = [];
...
omvandla.onclick = function (){
if(isNaN(input.value)){
alert ("Use numbers");
}
else{
console.log(...);
array.push(input.value);
}
};
For more information about JavaScript arrays see here.

My JS is not running, shows POST error

I am writing an online loan calculator for practice. The data processing is all done on the client-side, however, JSFiddle wants me to use POST. Why is this? Could this be related to the fact that when the calculate button is clicked locally, the form just clears? The code in a JSFiddle: http://jsfiddle.net/TJonS/CuzSM/
Also, why isn't this calculating on click of the button? I have tried debugging multiple times, but Chrome is showing no errors.
Javascript:
function calculate(){
//get the elements
var amount = document.getElementById("amount");
var rate = document.getElementById("rate");
var duration = document.getElementById("duration");
//get the values of the elements
var a = parseFloat(amount.value);
var r = parseFloat(rate.value);
var d = parseFloat(duration.value);
//grab the outputable (readable(ha ha:))) variables
var principal = a;
var interest = r/100/12;
var time = d *12;
//now the calculation variables
var x = Math.pow(1+interest, payments);
var monthlypay = (principal*x*interest)/(x-1);
//if the result is a finite number, then display it. Else we're messed up!
if (isFinite(monthlypay)) {
//fill in outputs
payment.innerHTML = monthlypay.toFixed(2);
total.innerHTML = (monthlypay * payments).toFixed(2);
totalinterest.innerHTML = ((monthlypay*payments)-principal).toFixed(2);
//save the variables
save(amount.value, rate.value,duration.value, a.value, r.value, d.value, principal.value, total.value, totalinterest.value)
}
//else just make the outputs blank as can be.
else {
payment.innerHTML = "";
total.innerHTML = "";
totalinterest.innerHTML = "";
}
}
just put
return false;
at the bottom of your calculate function, to stop the default onClick behavior(of the button) performing a form post.
also...
is your if statement "if (isFinite(monthlypay)) {" actually getting focus?
this seems to be wiping the values every time.
else {
payment.innerHTML = "";
total.innerHTML = "";
totalinterest.innerHTML = "";
}
check your "isFinite(monthlypay)" function is returning true. (most probably never)
Button without post on click:
<input type="button" onclick="dosomething();" value="my button text" />

change div content based on three for elements

Hey guys,
I'm new to jQuery/js and having a hard time figuring this out.
There are two fields in a form of mine i want to do some calculations with, what i tried is this:
jQuery.fn.calculateit = function(){
var one = $("#one").val();
var two = $("#two").val();
//total
var total = one + two;
$("#total").text(total);
};
The values "one" and "two" can change at any time, and every time that happens i want the total to change. So I wrote the method above, but I have no idea how to have it called any time something happens with the two fields.
Any ideas?
Maybe I'm on the wrong track, so any suggestions are welcome!
Thanks!
Here you go:
$("#one, #two").change(function() {
calculateit();
});
var calculateit = function() {
var one = parseInt($("#one").val(), 10);
var two = parseInt($("#two").val(), 10);
//total
var total = one + two;
$("#total").text(total);
};
Or, if you prefer, you can add calculateit to jQuery.fn and call it with $.calculateit().
Or, more concisely:
$("#one, #two").change(function() {
var one = parseInt($("#one").val(), 10);
var two = parseInt($("#two").val(), 10);
//total
var total = one + two;
$("#total").text(total);
});

Categories

Resources