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
Related
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.
I am trying to output only articles if authorsId = authorId.
Beside that the whole function works exactly as I want, here it is:
The general idea is to limit access to only own articles.
So, my question is: how do I limit the results to show only articles written by the owner of the page we are on (authorsId = authorId).
function ArticlesListReturn(returned) {
xml = returned.documentElement;
var rel = document.getElementById('related_category_articles');
rel.options.length = 0;
var status = getXMLData('status');
var title = '';
var id = '';
var authorid = '';
if (status == 0) {
alert("%%LNG_jsArticleListError%%" + errormsg);
} else {
var authorid = document.getElementById("authorid").value; // Serge
// authorsid = getNextXMLData('authors',x);
for (var x = 0; x < xml.getElementsByTagName('titles').length; x++) {
title = getNextXMLData('titles', x);
id = getNextXMLData('ids', x);
authorsid = getNextXMLData('authors', x);
alert(authorsid) // authors of each article - it returns the proper values
alert(authorid) // author of the page we are on - it returns the proper value
var count = 0;
rel.options[x] = new Option(title, id, authorid); // lign that returns results
title = '';
id = '';
authorid = '';
}
}
I suspect the problem is when you try performing a conditional statement (if/then/else) that you are comparing a number to a string (or a string to a number). This is like comparing if (1 == "1" ) for example (note the double quotes is only on one side because the left would be numeric, the right side of the equation would be a string).
I added a test which should force both values to be strings, then compares them. If it still gives you problems, make sure there are no spaces/tabs added to one variable, but missing in the other variable.
Also, I changed your "alert" to output to the console (CTRL+SHIFT+J if you are using firefox). The problem using alert is sometimes remote data is not available when needed but your alert button creates a pause while the data is being read. So... if you use alert, your code works, then you remove alert, your code could reveal new errors (since remote data was not served on time). It may not be an issue now, but could be an issue for you going forward.
Best of luck!
function ArticlesListReturn(returned) {
xml = returned.documentElement;
var rel = document.getElementById('related_category_articles');
rel.options.length = 0;
var status = getXMLData('status');
var title = '';
var id = '';
var authorid = '';
if (status == 0) {
alert("%%LNG_jsArticleListError%%" + errormsg);
} else {
var authorid = document.getElementById("authorid").value; // Serge
// authorsid = getNextXMLData('authors',x);
for (var x = 0; x < xml.getElementsByTagName('titles').length; x++) {
title = getNextXMLData('titles', x);
id = getNextXMLData('ids', x);
authorsid = getNextXMLData('authors', x);
console.log("authorsid = "+authorsid); // authors of each article - it returns the proper values
console.log("authorid = "+authorid); // author of the page we are on - it returns the proper value
if( authorsid.toString() == authorid.toString() )
{
rel.options
var count = 0;
console.log( authorsid.toString()+" equals "+authorid.toString() );
rel.options[rel.options.length] = new Option(title, id, authorid); // lign that returns results
}
else
{
console.log( authorsid.toString()+" NOT equals "+authorid.toString() );
}
title = '';
id = '';
authorid = '';
}
Did you check the console for messages? Did it correctly show authorid and authorsid?
I have edited the script and made a couple of additions...
The console will tell you if the conditional check worked or not (meaning you will get a message for each record). See the "if/else" and the extra "console.log" parts I added?
rel.options[x] changed to equal rel.options[rel.options.length]. I am curious on why you set rel.options.length=0 when I would instead have done rel.options=new Array();
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();
I have a text field (not a date field) who contain simply a value such "2013-08-27" and my goal would be to reverse the order and get "27-08-2013". So is matter to re-arrange the content but I don't have enough javascript knowledge. I tried using some "date" variable but without success much probably because my field is not a date field.
The html related to the field look like this:
<input type="text" value="2013-08-27" name="my_field" id="my-field" readonly="">
If you can give me an example of code based of this:
var my_field = document.getElementById('my_field');
thank
PS: I precise I don't have access to html of this field because is located to a remote server. I can only interact by adding code in a JS file planned for that. The field have also a "readonly" property because is not planned for be modified.
This code should do the trick:
var revert = function(str) {
var parts = str.split("-");
var newArr = [];
for(var i=parts.length-1; p=parts[i]; i--) {
newArr.push(p);
}
return newArr.join("-");
}
var replaceValueInInputField = function(id) {
var field = document.getElementById(id);
field.value = revert(field.value);
}
var replaceValueInDomNode = function(id) {
var el = document.getElementById(id);
var value = el.innerHTML, newValue = '';
var matches = value.match(/(\d{4})-(\d{2})\-(\d{2})/g);
for(var i=0; m=matches[i]; i++) {
value = value.replace(m, revert(m));
}
el.innerHTML = value;
}
replaceValueInInputField("my-field");
replaceValueInDomNode("my-field2");
jsfiddle http://jsfiddle.net/qtDjF/2/
split('-') will return an array of number strings
reverse() will order array backwards
join("-") will join array back with '-' symbol
var my_field_value = document.getElementById('my_field').value;
my_field_value.split('-').reverse().join("-");
You can use the split function.
var my_field = document.getElementById('my_field').split("-");
the var my_field will be an array of string like : "YYYY,mm,dd"
and then you can re-arrange it in the order you want.
Try this
var date = document.getElementById("my-field").value;
//alert(date);
var sp = date.split("-");
alert(sp[2]+"-"+sp[1]+"-"+sp[0]);
With Jquery
var parts =$('#my-field').val().split("-");
$('#my-field').val(parts[2]+"-"+parts[1]+"-"+parts[0]);
Simple regex:
var res;
test.replace(/(\d\d\d\d)-(\d\d)-(\d\d)/,function(all,a,b,c){res=c+"-"+b+"-"+a;});
JSFiddle: http://jsfiddle.net/dzdA7/8/
You could try splitting the string into array and inverting it's items in a loop:
var my_field = document.getElementById('my_field').value.split("-"),
length = my_field.length,
date = [];
for(i = length - 1; i >= 0; i--){
date.push(my_field[i]);
}
console.log(date.toString().replace(/,/g,"-"));
I have 3 TextFields, called txtUSD, txtEUR, txtAUS. And a PopupList with the same values, minus the txt part, but I need to form the names of the TextFields to use based on the selection that the user made. So I've done this:
function btConvert_Click(event)
{
var amount = document.getElementById("txtAmount").value;
var rates = document.getElementById("lstConvertTo").value;
var from = "txt" + document.getElementById("lstFrom").options[document.getElementById('lstFrom').selectedIndex].text;
var to = "txt" + document.getElementById("lstConvertTo").options[document.getElementById("lstConvertTo").selectedIndex].text;
var curr_from = document.getElementById(from).value;
var curr_to = document.getElementById(to).value;
if(curr_from > curr_to)
{
amount * rates;
} else {
amount / rates;
}
alert(result);
}
But every time I try it I get this error:
mobile/main.js line 215: Result of expression 'document.getElementById(from)' [null] is not an object.
How should I make it?
From the error you're getting, it looks like there's a bug when generating the from variable.
You should consider storing document.getElementById('lstFrom') into it's own var, for brevity.