Calculate sum of textarea entries in an invoice - javascript

I'm getting close with this, I'm just having trouble getting my first entry and second entry etc to add together.
My first entry shows up in the text field, and my second entry does as well, but they don't add together, it just shows the total, subtotal and tax of my second entry at the bottom, not the sum of the first and second entry.
Text area looks like this
<textarea input type ="text" name = "textarea" id = "textarea" rows = "12" cols = "180" placeholder = "--Item Code-- --Item Name-- --Item Cost-- --Quantity-- --Subtotal-- --Tax-- --Total--"></textarea>
My document.getElementById looks like this
document.getElementById('textarea').value += ("\n")+("\n") + "--" + code + "--" + " " + " " + "--Item Name--" + "--" + itemName + "--" + " " + " " + "--" + cost +"--" + " " + " " + "--" + quantity + "--" + " " + " " + "--" + subtotal + "--" + " " + " " + " " + "--" + tax + "--" + " " + " " + "--" + total + "--";
So every time I hit my Add Item button, it'll keep adding my entries to the text field, but it won't add the sum of all those entries.
I won't post my whole code, but I'll give a snippet to give you an idea
var subtotal = document.getElementById("subtotal").value;
subtotal = cost * quantity; // multiplying cost by quantity = subtotal
var tax = document.getElementById("tax").value;
tax = subtotal * .07; // multiplying subtotal by tax(.7) = amount of tax owed
var total = document.getElementById("total").value;
total = tax + subtotal; //adding tax to subtotal = total value
document.getElementById("subtotal").value = subtotal;
document.getElementById("tax").value = tax;
document.getElementById("total").value = total;
How can I get the sum of all my entries? If you need me to post more code, I will. I just wanted to keep this post concise and to the point. .
EDIT:
I'm making an invoice, and the user enters
Below shows the layout of the page
Item Code (text field for user to enter info)
Item Name (text field for user to enter info)
Item Cost (text field for user to enter info)
Quantity (text field for user to enter info)
(Big text area here where the user's entries go. when I click add item for multiple entries, it shows what the user entered as a list. so:
First entry = 3 Ipod 200 1
Second entry = 2 Tv 400 1 ) < -- This is the middle of the page (textarea)
Subtotal (calculated value)
Tax (calculated value)
Total (calculated value)
I can calculate these fine for one value. And it adds the entries in the textarea. But my subtotal, tax and total field don't add the entries. (First entry + second entry etc)
So when I put in the second value at 400. It doesn't add that to the subtotal, tax and total of the first entry, it replaces the first entry in the calculated value portion, and puts the second entry as if the first entry never existed.
However, the textarea shows the multiple user entries.

var inputVal = $('textarea').val();
inputVal = inputVal.split('\n');
var total = 0;
for (var i = inputVal.length - 1; i >= 0; i--) {
if(inputVal[i] === ''){
continue;
}
var values = inputVal[i].split(' ');
total += parseInt(values[0],10) * parseInt(values[2],10);
};

Related

javascript count black spaces as 0?

I am building a script that is embedded in HTML to generate a report that extracts information from an internal company system.
The objective is to build some kind of a funnel, making the sum of records in each of the stages. For example, I have:
Processes in stage 1 = "3"
Processes in stage 2 = "5"
Processes in stage 3 = " "
Processes at stage 4 = "2"
Processes in stage 5 = " "
However, I have a problem when one of the stages is empty (it is not 0) because there is no stage in that specific process. When I try to add, for example, Stage 1 and Stage 3, it always returns an empty value, while it should give result 3 (3 + 0).
<p id="global_calc"></p>
<script>
{
var A = Stage1.system.count;
var B = Stage2.system.count;
var total = A + B;
}
document.getElementById("global_calc").innerHTML = "The total of this stage is: " + total;
</script>
The Stage.system.count is the internal system's variable that has the number I want to eventually sum with var total.
But, for example, if Stage1.system.count = 3 and Stage2.system.count = " ", total result in " " instead of 3. How can I make this to count the black space as a 0?
First it's probably worth checking what variables you have; any number + " " will always give you a string:
const x = 123 + " "; // "123 ";
const y = 123 + "" // "123"
We can see that in practice in your example:
{
var A = 3;
var B = " ";
var total = A + B;
}
document.getElementById("global_calc").innerHTML = "The total of this stage is: " + total;
console.log(("The total of this stage is: " + total).replace(/ /g, '*'))
<div id="global_calc"></div>
It seems like you're using undefined as part of the addition, which returns the value NaN:
{
var A = 3;
var B = undefined;
var total = A + B;
}
document.getElementById("global_calc").innerHTML = "The total of this stage is: " + total;
console.log(("The total of this stage is: " + total).replace(/ /g, '*'))
<div id="global_calc"></div>
We'll need more details to figure out exactly why you're getting " " for total.
If you want a function which converts number -> number and " " -> 0 then Number would do:
const x = 3;
const y = " ";
console.log(Number(x));
console.log(Number(y));

Showing an * next to smallest value in a table javascript

I am trying to find the smallest value of fuel consumption in my table. I am not sure how to find it.
I have a user input the amounts for 5 vehicles. The collection point is an object that has constuctor function with 5 properties. then I have stored the details of the five objects in an array of 5 objects.
when I try to write the code for obtaining the lowest number I get my display as the first with a * and the next lowest with a * and the next lowest as a *. All values after the lowest are blank. I just want the lowest as a *. below is the code after I have had the user input 5 times. All this is within a for loop. one of the properties calculates the consumption in the original object constuctor function.
for (var x = 1; x <= 5; x++) {
registrationPlateNumber = prompt("Please enter a 6 character registration number.", "");
while (String(registrationPlateNumber).length != 6) {
registrationPlateNumber = prompt("Invalid registration number! Please enter a 6 character registration number.", "");
}
fuelTankVolume = prompt("Please enter the volume of the vehicle's fuel tank in litres.", "");
fuelTankVolume = parseInt(fuelTankVolume);
while (isNaN(fuelTankVolume) || fuelTankVolume <= 0) {
fuelTankVolume = prompt("Invalid volume! Please enter the volume of the vehicle's fuel tank in litres.", "");
fuelTankVolume = parseInt(fuelTankVolume);
}
distanceTravelled = prompt("Please enter the distance the vehicle can travel on a full tank of fuel.", "");
distanceTravelled = parseInt(distanceTravelled);
while (isNaN(distanceTravelled) || distanceTravelled <= 0) {
distanceTravelled = prompt("Invalid distance! Please enter the distance the vehicle can travel on a full tank of fuel.", "");
distanceTravelled = parseInt(distanceTravelled);
}
VehicleArray[x] = new Vehicle(registrationPlateNumber, fuelTankVolume, distanceTravelled);
document.writeln("<tr>");
document.writeln("<td>" + VehicleArray[x].registrationPlateNumber + "</td>");
document.writeln("<td>" + VehicleArray[x].fuelTankVolume + "</td>");
document.writeln("<td>" + VehicleArray[x].distanceTravelled + "</td>");
document.writeln("<td>" + VehicleArray[x].fuelConsumption + "</td>");
if (VehicleArray[x].fuelConsumption < LowestConsumption) {
LowestConsumption = VehicleArray[x].fuelConsumption;
MostEfficient = LowestConsumption;
MostEfficient = x;
}
if (x == MostEfficient) {
document.writeln("<td>*</td>");
}
else if (x != MostEfficient) {
document.writeln("<td> </td>");
}
}
In your approach, each time you add an element to the VehicleArray, you are checking if this element is the minimum compared to the previously added ones, and if it is, you are marking it directly with an asterisk.
However, there could be elements that have not been added yet that have smaller values. But as the for loop did not reach these yet, the current element is marked with an asterisk.
Then at the next iteration, if the next vehicle's fuel consumption is even lower, it will also be marked with an asterisk, and so on.
The fix for this is to use two for loops: one for filling the array and getting the minimum, and then another one for displaying the elements in the table.
//first loop: add all elements to the array and get the index of the minimum
var MostEfficient = 0;
for (var x = 1; x <= 5; x++){
//code for user prompts...
//adding the vehicle to the array
VehicleArray[x] = new Vehicle(registrationPlateNumber, fuelTankVolume, distanceTravelled);
//checking if it is the minimum for now; only the final minimum will be used in the next loop
if (VehicleArray[x].fuelConsumption < LowestConsumption){
LowestConsumption = VehicleArray[x].fuelConsumption;
MostEfficient = x;
}
}
//second for loop to write the elements to the document
//now MostEfficient won't update anymore, and will point to the final minimum
for(var x = 1; x <= 5; x++)
document.writeln( "<tr>");
document.writeln( "<td>" + VehicleArray[x].registrationPlateNumber + "</td>");
document.writeln( "<td>" + VehicleArray[x].fuelTankVolume + "</td>");
document.writeln( "<td>" + VehicleArray[x].distanceTravelled + "</td>");
document.writeln( "<td>" + VehicleArray[x].fuelConsumption + "</td>");
if (x == MostEfficient){
document.writeln("<td>*</td>");
}
else if (x != MostEfficient){
document.writeln("<td> </td>");
}
}
Also, on a side note, why are you doing this?
MostEfficient = LowestConsumption;
MostEfficient = x;
Wrong variable name maybe? Otherwise the first statement is useless.
You can't do this in a single loop since you don't know the user's input before it's given.
Separating the algorithm in two loops should be better: one that fills up VehicleArray and one another that display the table. In between you'll need to find MostEfficient.
Since it seems like homework I'll not give you code as an answer but I can schematize:
loop:
-> fetching data and filling the array
-> finding the most efficient
-> displaying the table

My Javascript prompt runs before function even if prompt is located after the function

I wrote a small practice program that shows the times table for a prompted number.
I want the table to be shown after the user is asked for which number. If the user enters a different than -1 number, I want to ask for another number.
The sequence that I'm looking for is prompt the user, show the table, prompt the user show the table ... Unfortunately the sequence in which my program works is prompt the user, prompt the user, prompt the user ... AND JUST AFTER THAT show the tables for each input.
Obviously the code is not written in that way.
// get number to show time table for
var aNumber = prompt("Enter the number for time table or -1 to stop the program", "");
while(aNumber != -1) {
timeTableFrom(aNumber); // show time table for the first number
aNumber = prompt("Enter the number for time table or -1 to stop the program", ""); // ask for another number. HERE IS THE PROBLEM - THIS LINE RUNS BEFORE THE PREVIOUS ONE!
}
document.write("stopped");
function timeTableFrom(number)
{
for (var i = 0; i <= 10; i++)
{
document.write(number + " * " + i + " = " + number*i + "<br />");
}
}
// get number to show time table for
var aNumber = null;
var div = document.getElementById("textDiv");
setTimeout(enterNumber, 0);
function enterNumber()
{
aNumber = prompt("Enter the number for time table or -1 to stop the program", "");
if (aNumber != -1) {
timeTableFrom(aNumber); // show time table for the first number
setTimeout(enterNumber, 0);
}
else
div.innerHTML += "stopped"
}
function timeTableFrom(number)
{
for (var i = 0; i <= 10; i++)
{
div.innerHTML += number + " * " + i + " = " + number*i + "<br />";
}
}
<div id="textDiv">
</div>
#Teemu is correct. And I admit, it's a bit sloppy, but this should work. Try to avoid using document.write as it can have unpredictable results. Instead try other methods of output

jQuery unwanted sum result

I have a table head <th> that is set by default to 0:
<th id="total_price" style="text-align:center">0</th>
Now when, I add a new sold item, the price should be added to the value of the this <th>. So, if the new one is 20000, the value should be 20000+0=20000 and not 200000. And if I add another item, with price of 30 000 it would be now like 20000030 000.
This is jquery script:
var initial = $("#total_price").text();
console.log(initial);
var newPrice = initial + (res['price']);
console.log(newPrice);
$("#total_price").text(newPrice);
I tried this:
var initial = $("#total_price").text();
console.log(initial);
var newPrice = initial + +(res['price']);
console.log(newPrice);
$("#total_price").text(newPrice);
But still the same.
You need to parse the text (string) into a integer and then add it up. So do below for your calculations
var newPrice = parseInt(initial,10) + parseInt(res['price'],10);
Or else what you are trying would be a string concatenation and not a Sum
You can get More info Here
As I have already commented, when you read text from DOM elements, it is read as string and when you apply + operator to it, its is treated as concatenation and adddition.
Following is a simulation:
(function(){
var th = $("th");
var result = "";
result += "Direct addition: " + $(th[0]).text() + $(th[1]).text() + "<br/>";
result += "Type: " + typeof($(th[0]).text()) + "<br/>";
result += "Parse Int: " + (parseInt($(th[0]).text()) + parseInt($(th[1]).text())) + "<br/>";
$("#result").html(result);
})()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<table>
<tr>
<th>20000</th>
<th>0</th>
</tr>
</table>
<p id="result"></p>
Also do refer following post: parseInt vs unary plus

issue with adding values from array

I am writing a small application for the user to enter the name of a book and then its price, push the values of those to an array, output the book name and cost to the page and then display the total.
the issue I am having is with the total, for example:
If I write 2 as the value of each of the values, the "totalOutput" says 022222 instead of 10 as I would expect, I have tried a few different things and read a few articles on here but haven't found any to be much help or that useful.
these are the exact lines I am having issues with:
//go over each item in price and add up the total
price.forEach(function addNumber(value) {
total += value;
});
//write the total
totalOutput.innerHTML = "the total value of the books is " + total;
}
And incase you need it - here is my full javascript code:
//Book shop task
function trackBooks() {
//target the output ul and store in a variable
var output = document.getElementById("booksOutput");
//Setup the two arrays to hold the book names and their prices.
var books = [];
var price = [];
//declare a variable for working out the total
var total = 0;
//target the total output
var totalOutput = document.getElementById("totalOutput");
//set up a counter for the loop
var x = 0;
//setup the loop for entering the names of the books and their prices, for the sample, I have set the loop to run 5 times as stated in the pseudo code
for (var i = 0; i < 5; i++) {
//add one to the counter on each loop
x = x + 1;
//declare a variable to ask the user for the book name and the cost and push those values to their arrays we created above
var bookName = prompt("enter book name number " + x);
books.push(bookName);
var bookPrice = prompt("how much does book number " + x + " cost?");
price.push(bookPrice);
//create a variable to create new li tags on output
var newLi = document.createElement("li");
//add the required info to the new link
newLi.innerHTML = "book " + x + ": " + "<strong>" + books[i] + "</strong>" + " costs " + "<strong>" + price[i] + "</strong>";
//write out the name and price to the page
output.appendChild(newLi);
}
//go over each item in price and add up the total
price.forEach(function addNumber(value) {
total += value;
});
//write the total
totalOutput.innerHTML = "the total value of the books is " + total;
}
var bookPrice = prompt("how much does book number " + x + " cost?");
price.push(bookPrice);
prompt returns a string, and when you add a number (0) and a string ("2"), you get a string ("02"). You should cast to number here:
price.push(+bookPrice);
(unary + casts to a number)
You are adding Strings not a Numbers. For example:
"Hello " + "World";
Will output "Hello World".
"10" + "20";
will output "1020"
Instead you have to convert the String to a Number
Number("10") + Number("20");
will ouput 30
To apply this to your code:
price.push(Number(bookPrice));

Categories

Resources