issue with adding values from array - javascript

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

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

Sum values from an Array, JavaScript

Prompting the user for many inputs, storing it in an array, then printing summation , average, largest number, smallest number and bigger number than mean number.
I have defined a JavaScript variables called magicnumber which is a new Array , and print the value of array, like this:
var magicnumber = [];
mymagicNumber();
function mymagicNumber() {
//Specify the size of array
var size = parseInt(prompt("How many data values do you need have?"));
for (var i = 1; i <= size; i++) {
//sorted in array
var num = parseInt(magicnumber.push(prompt("Enter data value number " + i)));
var s = magicnumber.join(', ');
}
//Display array element
document.getElementById("demo1").innerHTML = "Your data : " + s + "<br>";
}
<div id="demo1"></div>
how I can summation it?
You can use Array#reduce() to get the sum
var magicnumber = [];
mymagicNumber();
function mymagicNumber() {
//Specify the size of array
var size = parseInt(prompt("How many data values do you need have?"));
for (var i = 1; i <= size; i++) {
var promptValue = prompt("Enter data value number " + i);
magicnumber.push(+promptValue);
}
var sum = magicnumber.reduce((a,b)=>{return a+b},0);
//Display array element
document.getElementById("demo1").innerHTML = "Your data : " + magicnumber.join(', ');
document.getElementById("sum").innerHTML = "The sum : " + sum;
}
<div id="demo1"></div>
<div id="sum"></div>
Here are 2 more ways to find the summation, without using for loop.
var magicnumber = [];
function mymagicNumber() {
//Specify the size of array
var size = parseInt(prompt("How many data values do you need have?"));
for (var i = 1; i <= size; i++) {
//sorted in array
var num = magicnumber.push(parseInt(prompt("Enter data value number " + i)));
}
var data = magicnumber.join(', ');
var s1 = magicnumber.reduce(function(acc, val) {
return acc + val;
});
var s2 = eval(magicnumber.join("+"));
//Display array element
document.getElementById("demo1").innerHTML = "Your data : " + data + "<br>";
document.getElementById("demo2").innerHTML = "Sum is: " + s1 + "<br>";
document.getElementById("demo3").innerHTML = "Sum is: " + eval(s2) + "<br>";
}
mymagicNumber();
<div id="demo1"></div>
<div id="demo2"></div>
<div id="demo3"></div>

Looking to randomly select, concatenate string of text stored in variable

Problem
In my scripts.js the variable var fullURL = not getting the actual text to be tweeted out in the teaser1, teaser2 and teaser3 that I've stored in a variable. I basically want one of the three teasers to be randomly selected when people click fa-twitter
scripts.js
function shareTeam(){
$(".fa-twitter").click(function(){
// Grabs the names of all the players in the span
// Sets a variable marking the indexOf each of the names
// If the index doesn't find a space, it returns -1, which returns the full name
// Otherwise it will return only what follows the space
var lastNames = $("li span").map(function() {
var name = $(this).text();
var index = name.indexOf(" ");
return index == -1 ? name : name.substring(index + 1);
}).get();
console.log(lastNames);
var regularNames = lastNames.slice(0, 3); // Same as below, but no shuffling
regularName1 = regularNames[0]; // Forward
regularName2 = regularNames[1]; // Forward
regularName3 = regularNames[2]; // Defenseman
// Find me a random number between 1 and 3
// Where 1 is the start number and 3 is the number of possible results
var teaser = "teaser";
var rand = Math.floor(Math.random() * 3) + 1;
console.log(rand);
// Concatenate the two strings together
teaseRand = teaser.concat(rand);
// These are the components that make up that fullURL
var baseURI = "https://twitter.com/intent/tweet?url=";
var twitterUsername = "stltoday";
var interactiveURL = "http://graphics.########.com/STLblues";
// Randomly generate one of three teasers
var teaser1 = regularName3 + " to " + regularName2 + " back to " + regularName1 + " — GOAL! Create your own all-team #STLBlues team: ";
var teaser2 = "I picked my #STLBlues dream team. See which players I've chosen and build your own: ";
var teaser3 = "My #STLBlues team will skate circles around yours! Pick your team: ";
// This is the full url that will be switched in and out
// var fullURL = baseURI+interactiveURL+"&via="+twitterUsername+"&text="+teaseRand;
var fullURL = baseURI+interactiveURL+"&via="+twitterUsername+"&text="+teaseRand;
// It needs to be encoded properly as well
var encodedURL = encodeURIComponent(fullURL)
console.log(fullURL);
console.log(encodedURL);
// Change the href to the link every time the Twitter button is clicked
var changeLink = $("link--twitter").attr("href", encodedURL);
// if (lastNames.length === 6) {
// } else {
// // Generic teaser
// var teaser4 = "Pick your #STLBlues dream team from 50 of the best #StLouisBlues to hit the ice: " + interactiveURL + " (via #stltoday)";
// }
});
}
Unfortunately this teaseRand value will be either "teaser1" or "teaser2" or "teaser3" and not the value of your variables teaser1 or teaser2 or teaser3 if that makes sense. For your requirement you will need to add the teasers to an array and then randomly access from it. For e.g. if the array is called teaser then you will need to do teaser[rand] and obviously you will need to calculate the rand from 0 to 2 instead 1 to 3 like you have done now.
Please check the codepen that i have created here
http://codepen.io/19sthil80/pen/VKPqkR?editors=1111
$(document).ready(function(){
var teasers = [];
// Grabs the names of all the players in the span
// Sets a variable marking the indexOf each of the names
// If the index doesn't find a space, it returns -1, which returns the full name
// Otherwise it will return only what follows the space
var lastNames = $("li span").map(function() {
var name = $(this).text();
var index = name.indexOf(" ");
return index == -1 ? name : name.substring(index + 1);
}).get();
console.log(lastNames);
var regularNames = lastNames.slice(0, 3); // Same as below, but no shuffling
regularName1 = regularNames[0]; // Forward
regularName2 = regularNames[1]; // Forward
regularName3 = regularNames[2]; // Defenseman
// Find me a random number between 1 and 3
// Where 1 is the start number and 3 is the number of possible results
var teaser = "teaser";
var rand = Math.floor(Math.random() * 3);
console.log(rand);
// Concatenate the two strings together
teaseRand = teaser.concat(rand);
// These are the components that make up that fullURL
var baseURI = "https://twitter.com/intent/tweet?url=";
var twitterUsername = "stltoday";
var interactiveURL = "http://graphics.########.com/STLblues";
// Randomly generate one of three teasers
var teaser1 = regularName3 + " to " + regularName2 + " back to " + regularName1 + " — GOAL! Create your own all-team #STLBlues team: ";
var teaser2 = "I picked my #STLBlues dream team. See which players I've chosen and build your own: ";
var teaser3 = "My #STLBlues team will skate circles around yours! Pick your team: ";
teasers.push(teaser1);teasers.push(teaser2);teasers.push(teaser3);
// This is the full url that will be switched in and out
// var fullURL = baseURI+interactiveURL+"&via="+twitterUsername+"&text="+teaseRand;
var fullURL = baseURI+interactiveURL+"&via="+twitterUsername+"&text="+teasers[rand];
// It needs to be encoded properly as well
var encodedURL = encodeURIComponent(fullURL)
console.log(fullURL);
console.log(encodedURL);
// Change the href to the link every time the Twitter button is clicked
var changeLink = $("link--twitter").attr("href", encodedURL);
// if (lastNames.length === 6) {
// } else {
// // Generic teaser
// var teaser4 = "Pick your #STLBlues dream team from 50 of the best #StLouisBlues to hit the ice: " + interactiveURL + " (via #stltoday)";
// }
});

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