calculate carriage on javascript invoice - javascript

Given the following: How would I go about making a function to calculate carriage based on user input (which I have already created with the id "carriage")?
/* Description: Update price function
* #param: $itemRow - Row Object
**/
var updatePrice = function ($itemRow) {
// Calculate the price of the row. Remove and $ so the calculation doesn't break
var price = $itemRow.find('#itemPrice').val().replace(",", "") * $itemRow.find('#itemQty').val();
var carriage = $itemRow.find('#carriage').val();
price = roundNumber(price, 2);
isNaN(price) ? $itemRow.find('#itemLineTotal').val("N/A") : $itemRow.find('#itemLineTotal').val(price);
update_total();
};
var update_total = function () {
var total = 0;
$('input#itemLineTotal').each(function (i) {
price = $(this).val().replace(",", "");
if (!isNaN(price)) total += Number(price);
});
total = roundNumber(total, 2);
$('input#invGrandTotal').val('\u20AC' + total);
};

First, some improvements your code:
You seem to use the same ID for inputs in multiple HTML table rows. HTML allows you to use an ID only once per document. In your case you should use classes instead of IDs.
You remove commas in all numbers. It is not clear if this is correct or not. Do you use the comma as thousands separator (then it is okay) or as decimal separator (then it is not)? This depends on your local number format.
You don't need the (custom?) function roundNumber(), you can use Number.toFixed() e.g. 10.toFixed(2) returns 10.00
In your update_total() function you remove the commas again, but you never added them when writing to each row's itemLineTotal field.
I recommend you to use a consistent coding style, e.g. you sometimes use camel case function names (updatePrice()), sometimes an underscore (update_total()).
In your code example, it looks like there is one carriage input per row. As this is not very common on invoices, I assumed that this was a mistake and there is only one such input in the whole invoice.
To calculate the grand total you have to calculate the sum of all itemLineTotals and then add the value of carriage. You should do that in update_total(). I created a fiddle which shows a working example, hope that helps:
http://jsfiddle.net/pascalockert/8G7mp/
(Perhaps you have to adapt the decimal and thousands separators as mentioned above. See lines 10, 11, 21 and 25. Also, please mind JavaScript's restrictions on floating point numbers)

Related

Change last names into numbers, which relate and display images

Im new to JavaScript and don't have the knowledge to write this myself yet. Any help would be great.
I'm creating pseudorandom illustration generator, comprised of 3 images. They'd be chosen by their name and displayed. Live update would be the best.
I'd like to have the user enter their last name (into a field) which will be changed into an individual set of 3 numbers. From those numbers I'd like the images to be chosen, the 1st from the first etc. then display them vertically respectively.
Any input is welcome, I'm sure there's an easier way of doing it. Thanks for your time.
Edit:
I'd like to change the last name that the user enters into a 3 digit number(000-999), then display 3 images based of the numbers given. If the number made is 015, then the first image displayed would be 000.jpg, the second 010.jpg and the third would be 005.jpg. Id like the same result each time a name is entered and I'd like to update on real time if possible. I hope this helps clear things up, I'm still trying to figure out the best way. Thanks
You can use the ASCII table to get the number matching with a letter.
Then, you can iterate on every char of the last name and sum it.
At the end, you might want to use the % (modulo) of the sum to get a value lesser than 1.000.
A tested code would be:
var lastName = "Connor";
var sum = 0;
for(var i=0; i<lastName.length;i++)
{
sum += lastName[i].charCodeAt(0);
}
sum = (sum%1000);
In your case, the result would be: 623
Then, you might want to get the files: 600.jpg, 020.jpg and 003.jpg
var firstPic = (sum + "").split('')[0] + "00.jpg";
var secondPic = "0" + (sum + "").split('')[1] + "0.jpg";
var thirdPic = "00" + (sum + "").split('')[2] + ".jpg";

How to round a number up and add numeric punctuation

I've got the following pen: http://codepen.io/anon/pen/LVLzvR
I cant quite figure out how to round the number up so you don't break the punctuation. I need to round the number up as I don't want to see a value like 33,333.,333
//ADDS PUNCTUATION EVERY THREE CHARACTERS
$('input.numericpunctuation').keyup(function(event){
var oNum= $(this).val(); // USE THIS NUMBER FOR CALCULATION
var num = oNum.replace(/,/gi, "").split("").reverse().join("");
var num2 = RemoveRougeChar(num.replace(/(.{3})/g,"$1,").split("").reverse().join(""));
console.log(num2);
console.log(oNum);
// the following line has been simplified. Revision history contains original.
$(this).val(num2);
});
function RemoveRougeChar(convertString){
if(convertString.substring(0,1) == ","){
return convertString.substring(1, convertString.length)
}
return convertString;
}
Example input event:
If I input 5555, is expect to see (and do see) 5,555. However if I add 5555.55 I get 5,555,.55. Ideally id like to round the number up removing the decimal.
The problem isn't just with decimals, you will get the wrong formatting also by entering non digits, e.g., clicking King Kong will result in Kin,g K,ong. So, what you probably want is to filter out non-digits, which can be done by changing the line var oNum= $(this).val(); to:
var oNum= $(this).val().match(/\d/g).join('');
The value inside the match function is a RegEx object - if you never used it before then congratulations!

JavaScript: Retrieve negative floating point number from string of mutiple sums

I have a simple app that allows me to caculate the total amount invoiced and deposited in a route. However I want to allow the user to input multiple values in a single input field; e.g:
500+50+36.5-45.2-10.
I have written a function that will retrieve this input and then split this string into elements of an array at the + sign and immediately parse the values to numbers and then add them and return the total the user inputs into each individual field. This is all well as long as the user does no use any sign other than +.
I have searched the use of regexp:
regular expression in javascript for negative floating point number result stored in array
Javascript Regular expression to allow negative double value?
but none of the results seem to work.
How could I make my code retrieve the values so that the negative values get passed into the array as negative values?
Here is a snippet of my Js code:
For the full code, visit my fiddle.
totalInvoiced: function () {
var a = A.invoiced.value;
var value1Arr = [];
value1Arr = a.split("+").map(parseFloat);
var value1 = 0;
value1Arr.forEach(function (value) {
value1 += value;
});
I really like PhistucK's solution, but here an alternative with regex:
value1Arr = a.split(/(?=\+|\-)/);
This will split it, but keeps the delimiter, so the result will be:
["500", "+50", "+36.5", "-45.2", "-10"]
A bit dirty, but maybe a.replace(/-/g, "+-").split("+"), this way, you add a plus before every minus, since the negative numbers just basically lack an operator.
You can use this pattern that splits on + sign or before - sign:
var str = '500+50+36.5-45.2-10';
console.log(str.split(/\+|(?=-)/));

Javascript is treating variables as Strings, why?

I have the variable y, which is a subtotal. Its value is different depending on what happens with the html, but throughout the script I declared it like this:
var y = 21.78;
etc. Why is it that on my last equation where I add up the total, it treats them as strings when I want to add the values?
var tax = (0.055*y).toFixed(2);
var totalprice = y+tax;
/* totalprice holds "21.781.20" instead of 22.98 */
According to:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number/toFixed
toFixed() returns:
A string representation of number that does not use exponential
notation and has exactly digits digits after the decimal place.
thus, y+tax is cast to a string since one of the operands is a string.
In my opinion, this would make sense as Javascript's intrinsic numeric types do not have the ability to store a specific number of decimal place digits, so a string would be the most appropriate data structure to store this with.
I would advise you do all your addition before calling toFixed(), since the method is most suitable for formatting display output.
var taxRate = 0.055;
var subtotal = 21.78;
var tax = (taxRate * subtotal).toFixed(2),
totalprice = ((1+taxRate) * subtotal).toFixed(2);
document.write(totalprice);
The .toFixed() method returns a string. Try applying that method as the last step after all other calculations.
Here's a simple fix. Put '+' in front of the tax variable to convert it to a number.
var y = 21.78;
var tax = (0.055*y).toFixed(2);
var totalprice = y+ (+tax);
totalprice === 22.98;
If you don't want any rounding errors when you use toFixed, then include this re-implementation of it in your script.
http://bateru.com/news/2012/03/reimplementation-of-number-prototype-tofixed/
In my experience, if there's any chance available, Javascript will see the "+" sign as concatenate rather than addition. It's driven me nuts on more than one occasion. I will generally do this rather than chance concatenation:
var totalprice = parseInt(y)+parseInt(tax);
When letter replaces value, multiply with 1 when you're in need of +.
var totalprice = (y*1) + tax .
Other operands work fine, it's just the + operand that needs special treatment when variable replace value.

Jquery - Sum bug with various price formats

I have problems to calculate price with jquery in various price formats (depending on the language).
With German: 1.375,50 € (Returns 1.38 €)
English format: €1,375.50 (don't work)
French format: 1 375,50 € (Returns 1.00 €)
Italian format: €1,375.50 (don't work)
Spanish format: € 1.375,50 (don't work)
Here is a link of my working demo : http://jsfiddle.net/QmTNZ/63/
And here is my code :
function ca(){
var $overall = 0;
$("tr.sum").each(function() {
var $qnt = $(this).find(".qty");
var $price = $(this).find("td").eq(2);
console.log($qnt + " | " + $price);
var sum = parseFloat($price.text().replace(",", ".")) * parseFloat($qnt.val().replace(",", "."));
if(isNaN(sum)) {
sum = 0;
}
$(this).find("td").eq(3).text(Math.round(sum * 100) / 100);
$overall += sum;
});
$("#total").text($overall);
}
$(function() {
ca();
$('input.qty').bind('change keyup',function(){ca();});
});
The price "td" can contain other texts, for example "Incl. 19% tax".
My questions here is how can I use a css class that englobe only the price, without the Euro Symbol, to use it in calculation, and how can I avoid the problems of the dot and comma in price calculation in all price formats.
(I'm always beginner in jquery....)
Thanks for help !
Regardless of anything else, your code is going to have to know the formatting rules for the locale, otherwise you won't be able to correctly format your resulting sum.
However, you can avoid worrying about the locale differences in the main body of your code by separating out the price data from the price display. One way you can do that is with a data-* attribute on the element containing the price display.
For instance, let's suppose your row looks like this currently:
<tr><td>Widget</td><td>1</td><td>1 375,50 €</td></tr>
There, the 3rd cell contains the price as text with the various formats. Now, when outputting the table, if you include the price as a data-price attribute in a known, specific format, you avoid all this hassle:
<tr><td>Widget</td><td>1</td><td data-price="1375.5">1 375,50 €</td></tr>
You can then access it via attr("data-price"):
var thisPrice = parseFloat($(this).find("td:eq(2)").attr("data-price"));
This gets you the prices in a nice reliable way.
But again, in the end, you'll need to know the locale rules in order to display $overall in the correct format.

Categories

Resources