jQuery unwanted sum result - javascript

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

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));

Why do i see the NaN for total price?

I ahve already the script almost finished, but the total price is not showing up i still see NaN as results for the total price, why is this? and how can i quick fix this?
http://jsfiddle.net/9zPTA/135/
This is my jquery code:
$("input").on("keyup", function () {
var $input = $(this);
var howMany = parseInt($input.val());
var unitAmount = parseInt($input.parent().prev().text().replace("€", ""));
var total = howMany ? howMany * unitAmount : 0;
$input.parent().next().text("€ " + total);
var total = 0;
$("tbody tr td:last-child").each(function() {
total += parseInt($(this).text().replace("€","") || 0);
});
$("#total").html("€ " + total);
});
Your selector, and the brackets typo, are the problems. The brackets typo on parseInt
total += parseInt($(this).text().replace("€","") || 0);
parses $(this).text().replace("€","") || 0 which is not what you want.
Also, you were erroneously including the final row's <td> (which holds the current total!) in your total calculation. This resulted in the increasing total you were experiencing.
Change
$("tbody tr td:last-child")
to
$(".tdPrice.tdDarker")
Try this:
var total = 0;
$(".tdPrice.tdDarker").each(function() {
var val = parseInt($(this).text().replace("€",""));
total += isNaN(val) ? 0 : val;
});
$("#total").html("€ " + total);
Aside: Sometimes you have entries with no money value, like
<td class="tdPrice"> <div id="u_KiloFineSilver"></div></td>
versus
<td class="tdPrice">€ 10 <div id="u_barFineSilver"></div></td>
which will cause an NaN in the subtotal, but with my solution above the final total will not be NaN.
How can I hide the "0" value if someone enters, for example, 3 and then hits backspace?
Change
$input.parent().next().text("€ " + total);
to
$input.parent().next().text("€ " + (total > 0 ? total : ""));
Demo: http://jsfiddle.net/9ka2u5px/1/
Change total += parseInt($(this).text().replace("€","") || 0); to total += parseInt($(this).text().replace("€","") | 0);

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));

Calculate sum of textarea entries in an invoice

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);
};

insert into item.innerHTML

I've got a div remaining
remaining.innerHTML = "You have NUMBER remaining SECOND VARIABLE"
I know I can change innerHTML by just doing remaining.innerHTML = "new string" but I'm wondering using Javascript how would I inject a new value for NUMBER into the innerHTML without knowing NUMBER's index or value? However the non-variable contents e.g You have and remaining are constant.
Using string concatenation:
var number = 1;
var secondVariable = 2;
remaining.innerHTML = "You have " + number + " remaining " + secondVariable;
// results in "You have 1 remaining 2";
You can use the replace() method on the string, to replace your markers by their values.
For example, if you use this portion of code :
var str = "You have NUMBER remaining SECOND VARIABLE";
var new_str = str.replace('NUMBER', 150).replace('SECOND VARIABLE', 'plop');
The new_str variable will have as value :
"You have 150 remaining plop"
Which, applied to your specific case, would give something such as this :
remaining.innerHTML = "You have NUMBER remaining SECOND VARIABLE".replace('NUMBER', 150).replace('SECOND VARIABLE', 'plop');
remaining.innerHTML = "You have " + var1 + " remaining " + var2;
Something like
var no1 = 5;
var no2 = 10;
remaining.innerHTML = "You have " + no1 + " remaining " + no2;

Categories

Resources