Adding together any number of items in an array with Javascript - javascript

I am learning Javascript and currently having an issue creating an application. I want to create a webpage that will take the values entered in a textbox, and place them inside an array. Then, I want to create a function that will add the values together. I am nearly complete, but I am having a tough time figuring out how to create a function that will add together the array items. My biggest issue is that any number of values can be entered into the page, and all the documentation I can find is based on having a pre-set array. Here is my code:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Numbers</title>
</head>
<body>
<section>
<header class="header m-2" id="myForm">Numbers App</header>
<section class="row m-2">
<label class="inputLabel">Number: <input type="number" id="numInput"></label>
</section>
<button class="button m-1" onclick="displayText(); addNum(); testCount();" id="addButton">Add Number</button>
<button class="button m-1" disabled>Calculate</button>
<button class="button m-1" onclick="resetPage();">Reset</button>
</section>
<section id="numForm">
<div class="numLabel m-2" id="numLabel">Numbers Added: </div>
<p class="m-2 mt-3" id="numValue"></p>
</section>
<script src="script.js"></script>
</body>
</html>
JS:
//Display "Numbers Added: "
function displayText() {
document.getElementById("numLabel").style.display = "block";
}
//Add the entered values into the array
let numArray = [];
function addNum() {
let num = document.getElementById("numInput").value;
numArray.push(num);
document.getElementById("numValue").innerHTML = numArray.join(" ");
}
//Testing count function
function testCount() {
for(count = 0; count > 2; count++) {
console.log("this works");
}
}
//Reset the page
function resetPage() {
//Clear input field
document.getElementById("numInput").value = "";
//Hide "Numbers Added: "
document.getElementById("numLabel").style.display = "none";
//Clear array items
numArray = [];
document.getElementById("numValue").innerHTML = "";
}

Edit:
To display the addition can just use something like:
const array1 = [1, 2, 3, 4];
const result = array1.reduce((acc, curr) => parseInt(curr) + parseInt(acc));
let additionDisp = array1.join(" + ") + " = " + result;
console.log(additionDisp);

You need to declare your add function first, parse your string input to integer value and perform a reduction to get the sum
//Add the entered values into the array
let numArray = [];
//Display "Numbers Added: "
function displayText() {
var result = numArray.reduce((acc, curr) => parseInt(curr) + parseInt(acc), 0);
var numSumString = "";
for (data of numArray) {
numSumString = data + " + " + numSumString;
}
document.getElementById("numLabel").innerHTML = "Numbers Added:" + numSumString.substring(0, numSumString.length - 2) + "=" + result;
}
function addNum() {
let num = document.getElementById("numInput").value;
numArray.push(num);
document.getElementById("numValue").innerHTML = numArray.join(" ");
}
//Reset the page
function resetPage() {
//Clear input field
document.getElementById("numInput").value = "";
//Hide "Numbers Added: "
document.getElementById("numLabel").style.display = "none";
//Clear array items
numArray = [];
document.getElementById("numValue").innerHTML = "";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Numbers</title>
</head>
<body>
<section>
<header class="header m-2" id="myForm">Numbers App</header>
<section class="row m-2">
<label class="inputLabel">Number: <input type="number" id="numInput"></label>
</section>
<button class="button m-1" onclick="addNum();" id="addButton">Add Number</button>
<button class="button m-1" onclick="displayText();">Calculate</button>
<button class="button m-1" onclick="resetPage();">Reset</button>
</section>
<section id="numForm">
<div class="numLabel m-2" id="numLabel">Numbers Added: </div>
<p class="m-2 mt-3" id="numValue"></p>
</section>
<script src="script.js"></script>
</body>
</html>

Use Array.prototype.reduce.
const array = [0, 42, 101, 5, 2];
const total = array.reduce((sum, x) => sum + x);
console.log(total);

Related

Why does dynamically creating list items not work for the 10th item?

I am dynamically creating tabs as items of a list. For that I am using an input field called 'amount'. But I noticed some unwanted behavior for the 10th item. When using the arrow keys to increase or decrease the value of 'amount' the 10th item gets skipped and only gets created when I increase the value to 11, which creates both the 10th and 11th value at the same time. Every other value seems to work fine. Even inputting the number 10 and pressing enter works as intended, which is why I am even more confused.
This is my code:
const tabs = document.getElementById("tabs");
const amount = document.getElementById("amount");
var prevAmount = 0;
amount.addEventListener("change", function () {
if (amount.value < 1) {
amount.value = 1;
}
if (amount.value > prevAmount) {
while (tabs.children.length < amount.value) {
var newTab = document.createElement("li");
newTab.textContent = tabs.children.length + 1;
newTab.setAttribute("class", "tab");
tabs.appendChild(newTab);
}
} else {
while (tabs.children.length > amount.value) {
tabs.removeChild(tabs.lastChild);
}
}
prevAmount = amount.value;
});
amount.dispatchEvent(new Event("change"));
<!DOCTYPE html>
<html lang="en">
<body>
<div id="main-container">
<div id="amount-and-tabs-container">
<div class="container" id="amount-container">
<label id="amount-label" for="amount">Amount:</label>
<input type="number" id="amount" value="1" min="1">
</div>
<div class="container" id="tabs-container">
<ul class="tabs" id="tabs"></ul>
</div>
</div>
</div>
<!--<script src="form.js" defer></script>-->
<script src="tabs.js"></script>
</body>
</html>

Multiply a variable and store that value/output to screen

I have tried a bunch of ways to get this to work. I'm not a coder, and I have a frankensteined abomination of a counter program I put together as a replacement for our expensive counters that kept breaking on us (basically you input a value at the start of the day, and based on that value a calculation is done for the GOAL for the day).
I now want to add a GOAL BY LUNCH field/display that - however simply doing something like
var lunchgoal = goal * 0.69;
And then putting it on the page like I have with the goal field, does not seem to work.
I can either get it to display 0 - which seems like its displaying just the basic 0 value of goal before it is being incremented, or NaN - not a number.
So I thought I need to convert it to a number before multiplying it, but I nothing has worked for me for that. Right now I'm guessing it may be a matter of where they are contained on the page? I find that part of this confusing honestly. Any help is much appreciated, I would have thought this would be fairly simple!
Thank you!
HTML
<html>
<style>
body {background-color: Black;}
p {color: white;}
</style>
<div class="container">
<p> SAMS VALUE: <span id="output"> </span>
</p>
<p style="font-size:110px"> GOAL: <span id="output2"> </span>
</p>
<button style="background-color:white;width:20%;height:15%;font-size: 60px" type="button" onClick="onClick()">ACTUAL</button>
<p style="font-size:110px">Actual Count: <span id="clicks">0</span>
</p>
<div class="row">
<div class="col-sm-4"/>
<div class="col-sm-4">
<div id="timeContainer" class="well well-sm">
<time id="timerValue"/>
</div>
<div id="timerButtons">
<button id="start" class="btn btn-success" disabled="disabled">START</button>
<button id="stop" class="btn btn-danger">STOP</button>
<button id="reset" class="btn btn-default">RESET</button>
</div>
<div class="col-sm-4 col-sm-4 col-md-4"/>
</div>
</div>
</div>
</html>
Script
<script type="text/javascript">
document.addEventListener("keyup", function(event) {
if (event.keyCode === 109) {
event.preventDefault();
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
}
});
document.addEventListener("keyup", function(event) {
if (event.keyCode === 107) {
event.preventDefault();
document.getElementById("stop").click();
}
});
var clicks = 0;
function onClick() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
};
const input = parseInt(prompt("Enter a SAMS number: "));
var SAMSINPUT = input;
console.log(SAMSINPUT);
document.getElementById('output').innerHTML = SAMSINPUT;
var goal = 0;
var output2 = document.getElementById('output2');
//set interval for GOAL calculation
var samsInterval = setInterval(function doIncrement() {
if (clear == false) {
goal += 1;
output2.innerHTML = goal.toString();
}
}, SAMSINPUT * 1000);
var timerDiv = document.getElementById('timerValue'),
start = document.getElementById('start'),
stop = document.getElementById('stop'),
reset = document.getElementById('reset'),
clear = false,
t;
</script>
You have to do it in loop where goal is changing & you want this to change as well.otherwise it just stays on 0. i shortened the timer for demo purpose
document.addEventListener("keyup", function(event) {
if (event.keyCode === 109) {
event.preventDefault();
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
}
});
document.addEventListener("keyup", function(event) {
if (event.keyCode === 107) {
event.preventDefault();
document.getElementById("stop").click();
}
});
var clicks = 0;
function onClick() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
};
const input = parseInt(prompt("Enter a SAMS number: "));
var SAMSINPUT = input;
// console.log(SAMSINPUT);
document.getElementById('output').innerHTML = SAMSINPUT;
var goal = 0;
var output2 = document.getElementById('output2');
//set interval for GOAL calculation
var samsInterval = setInterval(function doIncrement() {
if (clear == false) {
goal += 1;
output2.innerHTML = goal.toString();
var lunchGoalNumber = goal * 0.69;
var output3 = document.getElementById("output3")
output3.innerHTML = lunchGoalNumber;
}
}, SAMSINPUT * 25);
var timerDiv = document.getElementById('timerValue'),
start = document.getElementById('start'),
stop = document.getElementById('stop'),
reset = document.getElementById('reset'),
clear = false;
<div class="container">
<p> SAMS VALUE: <span id="output"> </span></p>
<p style="font-size:50px"> GOAL: <span id="output2"> </span></p>
<p style="font-size:50px"> Lunch/GOAL: <span id="output3"> </span></p>
<button style="background-color:white;width:35%;height:15%;font-size: 60px" type="button" onClick="onClick()">ACTUAL</button>
<p style="font-size:50px">Actual Count: <span id="clicks">0</span></p>
<div class="row">
<div class="col-sm-4"></div>
<div class="col-sm-4">
<div id="timeContainer" class="well well-sm">
<time id="timerValue"></time>
</div>
<div id="timerButtons">
<button id="start" class="btn btn-success" disabled="disabled">START</button>
<button id="stop" class="btn btn-danger">STOP</button>
<button id="reset" class="btn btn-default">RESET</button>
</div>
<div class="col-sm-4 col-sm-4 col-md-4"></div>
</div>
</div>
</div>
</body>

I want to display the id of the posted content, it is currently expressed using a variable, so I want to display it using the array index

I'm beginner of javascript. Now, I create a application of list.
The content you want to display id "id + element".
I want to display it using the array index but using variable now.
expected
1:first value
2:second value
3:third value
...
This is code.
html
<body>
<h1>todo list</h1>
<div>
<input type="text" id="item">
<button type="button" id='click-function'>Add</button>
</div>
<ul id="todoList"></ul>
<script src="index.js"></script>
</body>
js
const myfunc = document.getElementById('click-function');
let i = 0;
myfunc.addEventListener('click',function(){
let todoItems = [];
let todoItem = document.getElementById('item').value;
todoItems.push(todoItem);
todoItems.forEach((element,index,array) => {
let li = document.createElement('li');
li.textContent = i + element;
document.getElementById('todoList').appendChild(li);
i++;
})
})
Updated your code snippet see the working demo below:
const myfunc = document.getElementById('click-function');
let i = 0;
myfunc.addEventListener('click',function(){
let todoItems = [];
let todoInput = document.getElementById('item');
let todoItem= todoInput.value;
todoInput.value='';
todoItems.push(todoItem);
todoItems.forEach((element,index,array) => {
let li = document.createElement('li');
li.textContent = (i+1)+' ' + element;
document.getElementById('todoList').appendChild(li);
i++;
});
})
<body>
<h1>todo list</h1>
<div>
<input type="text" id="item">
<button type="button" id='click-function'>Add</button>
</div>
<ul id="todoList"></ul>
</body>
Explanation:
Js Array has a starting index of 0 so you need to increment the current index by 1 each time you want to display it to the user.
Suggestion:
Instead of printing the index via code, I would suggest you to <ol> (ordered list) in place of <ul> (unordered list), which will do the work for you.
const myfunc = document.getElementById('click-function');
let i = 0;
myfunc.addEventListener('click',function(){
let todoItems = [];
let todoInput = document.getElementById('item');
let todoItem= todoInput.value;
todoInput.value='';
todoItems.push(todoItem);
todoItems.forEach((element,index,array) => {
let li = document.createElement('li');
li.textContent = element;
document.getElementById('todoList').appendChild(li);
i++;
});
})
<body>
<h1>todo list</h1>
<div>
<input type="text" id="item">
<button type="button" id='click-function'>Add</button>
</div>
<ol id="todoList"></ol>
</body>
You have get rid of forEach inside which is redundant.
const myfunc = document.getElementById('click-function');
let count = 0;
let todoItems = [];
myfunc.addEventListener('click',function(){
let todoItem = document.getElementById('item').value;
let li = document.createElement('li');
li.textContent = count++ +' : '+ todoItem;
document.getElementById('todoList').appendChild(li);
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<body>
<h1>todo list</h1>
<div>
<input type="text" id="item">
<button type="button" id='click-function'>Add</button>
</div>
<ul id="todoList"></ul>
<script src="index.js"></script>
</body>
</body>
</html>

How to properly execute a function within an event listener?

Every time a user clicks a button, the letter in that button gets compared with the list item button. I'm testing my code out and it seems that the code in the checkLetter function in my javascript file is not working.
This is my HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Wheel of Success!</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="css/styles.css" rel="stylesheet">
</head>
<body>
<div class="main-container">
<div id="overlay" class="start">
<h2 class="title">Wheel of Success</h2>
<a class="btn__reset">Start Game</a>
</div>
<div id="banner" class="section">
<h2 class="header">Wheel of Success</h2>
</div>
<div id="phrase" class="section">
<ul></ul>
</div>
<div id="qwerty" class="section">
<div class="keyrow">
<button>q</button><button>w</button><button>e</button><button>r</button><button>t</button><button>y</button><button>u</button><button>i</button><button>o</button><button>p</button>
</div>
<div class="keyrow">
<button>a</button><button>s</button><button>d</button><button>f</button><button>g</button><button>h</button><button>j</button><button>k</button><button>l</button>
</div>
<div class="keyrow">
<button>z</button><button>x</button><button>c</button><button>v</button><button>b</button><button>n</button><button>m</button>
</div>
</div>
<div id="scoreboard" class="section">
<ol>
<li class="tries"><img src="images/liveHeart.png" height="35px" width="30px"></li>
<li class="tries"><img src="images/liveHeart.png" height="35px" width="30px"></li>
<li class="tries"><img src="images/liveHeart.png" height="35px" width="30px"></li>
<li class="tries"><img src="images/liveHeart.png" height="35px" width="30px"></li>
<li class="tries"><img src="images/liveHeart.png" height="35px" width="30px"></li>
</ol>
</div>
</div>
</body>
<script src="app.js"></script>
</html>
This is my Javascript:
let missed=0;
const qwertyID=document.getElementById('qwerty');
const phraseID=document.getElementById('phrase');
const buttonElement=document.getElementsByClassName("btn__reset")[0];
const overLay=document.getElementById('overlay');
phraseArray=["Hey man","What the heck","Western University","Is that cool?","What is that?"];
const ul=document.getElementsByTagName('UL')[0];
//picks random phrase from phraseArray
//breaks phrase into character array
//returns arr---character array to be displayed
function getRandomPhraseAsArray(array) {
index = Math.floor((Math.random() * array.length))
let str=array[index];
let arr=[...str];
console.log(arr);
return arr;
}
//appends each character as list items in ul
//takes arr in parameter
function addPhraseToDisplay(characterArray) {
for (let i=0; i<characterArray.length; i+=1) {
let char=characterArray[i];
listItem=document.createElement('LI');
listItem.textContent=char;
if (char!==" ") {
listItem.className="letter";
}
ul.appendChild(listItem);
}
}
function checkLetter(button) {
letterFound=button.textContent;
letter=document.getElementsByClassName('letter');
for (let i=0;i<letter.length;i+=1) {
if (letter[i].textContent===letterFound) {
console.log("hello");
} else {
return null;
}
}
}
qwertyID.addEventListener('click', (e)=>{
e.target.className="choosen";
const button=e.target;
checkLetter(button);
});
//stores arr (character array) from function into variable
//inputs variable (character array) into new function
let phraseDisplayed=getRandomPhraseAsArray(phraseArray);
addPhraseToDisplay(phraseDisplayed);
//listener event to button to hide overlay
buttonElement.addEventListener('click', ()=> {
overLay.style.display="none";
});
As you can see, "hello" is not getting outputted to the console. I'm using the checkButton function within the qwertyID event listener, and I have a feeling there must be an issue with the scope of the button variable.
The instructions for this project asked me to input the button element as an argument in my checkButton function, so I can't change that aspect of my code. I was wondering if anyone could point out my problem?
Some words in phraseArray start with a capital letter. So if the user pushes w and your code compares it to W it won't ever evaluate to true.
To fix this you need to convert the input to a lower case letter first.
letterFound=button.textContent.toLowerCase();
Furthermore after the first test fails, you script won't check the remaining letters because you're returning from the function using return null;
Get rid of it and use this instead:
function checkLetter(button) {
letterFound = button.textContent.toLowerCase();
letter = document.getElementsByClassName('letter');
for (let i = 0; i < letter.length; i += 1) {
console.log(letter[i].textContent)
if (letter[i].textContent === letterFound) {
console.log("hello");
}
}
}
This function exits when the "return null;" line executes, so if is not the first in the list of buttons, it exits:
function checkLetter(button) {
letterFound = button.textContent;
letter = document.getElementsByClassName('letter');
for (let i = 0; i < letter.length; i += 1) {
if (letter[i].textContent === letterFound) {
console.log("hello");
} else {
//return null; //Change THIS
console.log("not found (yet)");
}
}
}

Copying the UI-Bootstrap code does not work? How do I use UI-Bootstrap?

I am trying to use components from the http://angular-ui.github.io/bootstrap/ page and am basically copying the code exacctly just to get the framework.
But it does not work seem to work, am I missing something general?
It is the exact same code and I have added the dependencies as far as I understand, which was the error in the other similar post.
For example with the carousel (ui.bootstrap.carousel), I copied the available html code into an html file index.html:
<!doctype html>
<html ng-app="ui.bootstrap.demo">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-animate.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-sanitize.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.3.0.js"></script>
<script src="example.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div ng-controller="CarouselDemoCtrl">
<div style="height: 305px">
<div uib-carousel active="active" interval="myInterval" no-wrap="noWrapSlides">
<div uib-slide ng-repeat="slide in slides track by slide.id" index="slide.id">
<img ng-src="{{slide.image}}" style="margin:auto;">
<div class="carousel-caption">
<h4>Slide {{slide.id}}</h4>
<p>{{slide.text}}</p>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<button type="button" class="btn btn-info" ng-click="addSlide()">Add Slide</button>
<button type="button" class="btn btn-info" ng-click="randomize()">Randomize slides</button>
<div class="checkbox">
<label>
<input type="checkbox" ng-model="noWrapSlides">
Disable Slide Looping
</label>
</div>
</div>
<div class="col-md-6">
Interval, in milliseconds: <input type="number" class="form-control" ng-model="myInterval">
<br />Enter a negative number or 0 to stop the interval.
</div>
</div>
</div>
</body>
</html>
The js code I have copied into a js file called example.js:
angular.module('ui.bootstrap.demo', ['ngAnimate', 'ngSanitize', 'ui.bootstrap']);
angular.module('ui.bootstrap.demo').controller('CarouselDemoCtrl', function ($scope) {
$scope.myInterval = 5000;
$scope.noWrapSlides = false;
$scope.active = 0;
var slides = $scope.slides = [];
var currIndex = 0;
$scope.addSlide = function() {
var newWidth = 600 + slides.length + 1;
slides.push({
image: '//unsplash.it/' + newWidth + '/300',
text: ['Nice image','Awesome photograph','That is so cool','I love that'][slides.length % 4],
id: currIndex++
});
};
$scope.randomize = function() {
var indexes = generateIndexesArray();
assignNewIndexesToSlides(indexes);
};
for (var i = 0; i < 4; i++) {
$scope.addSlide();
}
// Randomize logic below
function assignNewIndexesToSlides(indexes) {
for (var i = 0, l = slides.length; i < l; i++) {
slides[i].id = indexes.pop();
}
}
function generateIndexesArray() {
var indexes = [];
for (var i = 0; i < currIndex; ++i) {
indexes[i] = i;
}
return shuffle(indexes);
}
// http://stackoverflow.com/questions/962802#962890
function shuffle(array) {
var tmp, current, top = array.length;
if (top) {
while (--top) {
current = Math.floor(Math.random() * (top + 1));
tmp = array[current];
array[current] = array[top];
array[top] = tmp;
}
}
return array;
}
});
For better readability you can also find the code here: https://plnkr.co/edit/YZULMBb0br4IuhV4dUug?p=preview
When I run it, it just shows this on the page:
Slide {{slide.id}}
{{slide.text}}
Why?
Try, adding http: before the links, plunker loads these references directly, but when you load the urls directly in browser it wont work.
Sometimes not necessarily because almost all browsers take that as the default protocol if the user does not specify it directly
You need to add http:
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-animate.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-sanitize.js"></script>
<script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.3.0.js"></script>
<script src="example.js"></script>
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">

Categories

Resources