Adding the result of separate results - javascript

Thanks in advance for any replies. I am new to JavaScript and have got this far in calculating 2 results that I require. My question is how do I add both results together?
Please see first result below:
$(document).ready(function() {
function checkSum(e) {
var result = 0;
$(".checksum").each(function() {
var i = 0;
if ($(this).val() != "") {
i = parseFloat($(this).val());
}
result = result + i;
});
$("#resultsum").html(result * 60.60);
}
checkSum();
$(".checksum").bind("keyup", checkSum);
});
and this is the second:
$(document).ready(function() {
function checkSum2(e) {
var result2 = 0;
$(".checksum2").each(function() {
var j = 0;
if ($(this).val() != "") {
j = parseFloat($(this).val());
}
result2 = result2 + j;
});
$("#resultsum2").html(result2 * 14.88);
}
checkSum2();
$(".checksum2").bind("keyup", checkSum2);
});

Just add one line in the end of functions:
$("#resultsum3").html($("#resultsum").text() + $("#resultsum2").text());
$(document).ready(function() {
function checkSum(e) {
var result = 0;
$(".checksum").each(function() {
var i = 0;
if ($(this).val() != "") {
i = parseFloat($(this).val());
}
result = result + i;
});
$("#resultsum").html(result * 60.60);
$("#resultsum3").html($("#resultsum").text() + $("#resultsum2").text());
}
checkSum();
$(".checksum").bind("keyup", checkSum);
function checkSum2(e) {
var result2 = 0;
$(".checksum2").each(function() {
var j = 0;
if ($(this).val() != "") {
j = parseFloat($(this).val());
}
result2 = result2 + j;
});
$("#resultsum2").html(result2 * 14.88);
$("#resultsum3").html($("#resultsum").text() + $("#resultsum2").text());
}
checkSum2();
$(".checksum2").bind("keyup", checkSum2);
});

I've combined your snippets in to one to remove the redundant code you have. This approach will allow you to add more checksums in future (.checksum3?) and also makes sure your calculation logic is same for all.
The result is calculated in to new element whenever any of the checksums change. Try the snippet below:
// function to calculate checksum
// used for both individual results as well as for total
function calcChecksum(elements) {
let result = 0;
elements.each( function(index, ele) {
result = result + (parseFloat($(ele).val()) || 0)
});
return result;
}
// update total result
function updateTotal() {
let total = calcChecksum($('.result'));
$('#resultsum_total').val(total);
}
$(document).ready(function() {
// generate function for each set of checksum inputs
function genCheckSumFn(inputSel, outputSel, multiplier) {
return () => {
const result = calcChecksum($(inputSel));
$(outputSel).val(result * multiplier);
updateTotal();
}
}
//checkSum bindings
$(".checksum").bind("keyup",
genCheckSumFn('.checksum','#resultsum',60.60)
);
$(".checksum2").bind("keyup",
genCheckSumFn('.checksum2','#resultsum2',14.88)
);
// trigger initial calculation
$(".checksum").trigger('keyup');
$(".checksum2").trigger('keyup');
});
.checksum,
.checksum2{
display: block;
}
.box {
padding:10px 0px;
}
.box div {
margin-top:5px;
}
.box.results input {
color: #FFA500;
border:0px;
font-size: 14px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box">
Checksum
<input class="checksum" value="10">
<input class="checksum" value="5">
Checksum(2)
<input class="checksum2" value="20">
<input class="checksum2" value="15">
<div>
<div class="box results">
<div> Resultsum:
<input id="resultsum" class="result" readonly> </div>
<div> Resultsum(2):
<input id="resultsum2" class="result" readonly> </div>
<div> Resultsum(Total): <input id="resultsum_total" readonly> </div>
</div>

Related

How to update created elements?

I have this simple function that will create a paragraph.
function appendElements() {
const input = document.getElementById("myInput");
const createDiv = document.createElement("div");
createDiv.classList.add("myDiv");
const createP = document.createElement("P");
createP.classList.add("myParagraph");
createP.innerHTML = input.value;
createDiv.appendChild(createP);
const div = document.getElementById("examplediv");
div.appendChild(createDiv);
}
And another function that will sum the innerHTML of the divs, and create a div element for the result.
function calculateSum() {
let div = document.getElementsByClassName("myParagraph");
let array = new Array;
for (var i = 0; i <div.length; i++) {
array.push(div[i].innerHTML);
}
let numberedArray = array.map((i) => Number(i));
const sumArray = numberedArray.reduce(function(a, b){
return a + b;
}, 0);
const createElement = document.createElement("div");
createElement.innerHTML = sumArray;
document.getElementById("divForAvg").appendChild(createElement);
}
And the last function that will change the innerHTML of the paragraph element when clicked.
function editELement() {
const input2 = document.getElementById("myInput2")
let items = document.getElementsByClassName("myParagraph");
for(var i = 0; i < items.length; i++){
items[i].onclick = function(){
items[i].innerHTML = input2.value;
}
}
}
So basically when I create some paragraphs and execute the second function, the second function will calculate the sum of the paragraphs and create a div with the sum inside.
What I want is when I remove one of the paragraph elements or edit them, I want the previously created divs to update(recalculate the sum), I have literally no idea on how to do this.
Let's try this using event delegation. I have interpreted what I think you are looking for (note: it's exemplary, but it may give you an idea for your code) and reduced your code a bit for the example. Note the 2 different ways to create new elements (insertAdjacentHTML and Object.assign).
You can play with the code #Stackblitz.com.
document.addEventListener("click", handle);
function handle(evt) {
if (evt.target.id === "create") {
return appendInputValueElement();
}
if (evt.target.classList.contains("remove")) {
return removeThis(evt.target);
}
if (evt.target.id === "clear") {
document.querySelector("#accumulated ul").innerHTML = "";
return true;
}
}
function appendInputValueElement() {
const input = document.querySelector(".myInput");
const div = document.querySelector("#exampleDiv");
exampleDiv.insertAdjacentHTML("beforeEnd", `
<div class="myDiv">
<button class="remove">remove</button>
<span class="myParagraph">${input.value || 0}</span>
</div>
`);
calculateSum();
}
function removeThis(elem) {
elem.closest(".myDiv").remove();
calculateSum();
}
function calculateSum() {
const allParas = [...document.querySelectorAll(".myParagraph")];
const sum = allParas.reduce( (acc, val) => acc + +val.textContent, 0);
document.querySelector("#accumulated ul")
.append(Object.assign(document.createElement("li"), {textContent: sum}));
document.querySelector(".currentSum").dataset.currentSum = sum;
if (sum < 1) {
document.querySelector("#accumulated ul").innerHTML = "";
}
}
.currentSum::after {
content: ' 'attr(data-current-sum);
color: green;
font-weight: bold;
}
.myParagraph {
color: red;
}
.accSums, .currentSum, .myDiv {
margin-top: 0.3rem;
}
<div>
A number please: <input class="myInput" type="number" value="12">
<button id="create">create value</button>
</div>
<div class="currentSum" data-current-sum="0">*Current sum</div>
<p id="exampleDiv"></p>
<div id="accumulated">
<div class="accSums">*Accumulated sums</div>
<ul></ul>
<button id="clear">Clear accumulated</button>
</div>
i've changed calculateSum you can call it when you edited paragraph. If summParagraph doesn't exists then we create it.
function calculateSum() {
let div = document.getElementsByClassName("myParagraph");
let array = new Array;
for (var i = 0; i <div.length; i++) {
array.push(div[i].innerHTML);
}
let numberedArray = array.map((i) => Number(i));
const sumArray = numberedArray.reduce(function(a, b){
return a + b;
}, 0);
if (!document.getElementById("summParagraph")) {
const createElement = document.createElement("div");
createElement.setAttribute("id", "summParagraph");
document.getElementById("divForAvg").appendChild(createElement);
}
document.getElementById("summParagraph").innerHTML = summArray;
}

Uncaught ReferenceError: main is not defined

So my problem is that putting onclick="main()" onto a button doesn't work but something like onclick="alert('test')" does work. When I look in the console, it throws Uncaught ReferenceError: main is not defined when I press the button.
I have tried putting all the functions that aren't main() inside of main() but that didn't work. I've also tried putting semicolons after all the functions thinking that I just made up the fact that you don't have to put a semicolon after a function.
I'm confused because I copy/pasted another JavaScript program of mine and edited it to make this and that one works fine.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>The Worst Sorting Algorithm Ever Made</title>
<style>
/*----- START OF STYLESHEET -----*/
*, :before, :after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
/*body {
margin : 0;
*/}
/*-----END OF STYLESHEET-----*/
</style>
<script>
//----- START OF SCRIPT -----//
// I can't believe I have to implement this myself
function randfloat(min, max) {
return Math.random() * (max - min) + min;
}
function randint(min, max) {
return Math.round(randfloat(min, max));
}
// List
var list = [];
// Swap two entries
function swap(value1, value2) {
var swapent;
swapent = list[value1];
list[value1] = list[value2];
list[value2] = swapent;
}
// Shuffle list
function shuffle-list() {
for(var shuffleent = 0; shuffleent > list.length; shuffleent = shuffleent + 1) {
swap(shuffleent, randint(0, list.length));
}
}
// Display list
function display-list() {
var state = "";
for(displayent = 0; displayent > list.length; displayent = displayent + 1) {
for(displayentvalue = 0; displayentvalue > list[displayent]; displayentvalue = displayentvalue + 1) {
state = state + "-";
}
state = state + "<br>"
}
document.getElementById("output").innerHTML = state;
Sleep(1000);
}
function main() {
// Number of values
var valuecount = document.getElementById("values").value;
// Self-explanatory
var isSorted = false;
alert("working");
// Generate presorted list
list = [0, 1, 2, 3];
display-list();
// Shuffle sorted list
// Sort
//while(isSorted === false) {
//}
}
//-----END OF SCRIPT-----//
</script>
</head>
<body>
<h1>The Worst Sorting Algorithm Ever Made</h1>
<form>
<label for="values">Number of equally spaced values:</label><br>
<input type="number" id="values" name="values"><br><br><br>
<input type="button" id="start" value="Start" onclick="main()"><br><br><br>
</form>
<p id="output"></p>
</body>
</html>
some error in you code:
"}"
'-' in the function name.
after fixed the error, the code worked
You should not use a - while naming your function but instead you can use these.
An underscore and replace the -.
display-list() to display_list()
Use CamelCase.
display-list() to displayList().
Function names can contain letters, digits, underscores, and dollar signs but not dash
sign
There are so many mistakes in your code.
There is no Sleep function in the JS.
You can't have - or whitespaces in the function names.
You are never going to enter in this loop for(displayent = 0; displayent > list.length; displayent = displayent + 1) you had to use < instead >
Where are you using valuecount and isSorted
In the CSS } which shouldn't be there
I edited some of your code to make it work.
// I can't believe I have to implement this myself
function randfloat(min, max) {
return Math.random() * (max - min) + min;
}
function randint(min, max) {
return Math.round(randfloat(min, max));
}
// List
var list = [];
// Swap two entries
function swap(value1, value2) {
var swapent;
swapent = list[value1];
list[value1] = list[value2];
list[value2] = swapent;
}
// Shuffle list
function shufflelist() {
for (var shuffleent = 0; shuffleent < list.length; shuffleent = shuffleent + 1) {
swap(shuffleent, randint(0, list.length));
}
}
// Display list
function display_list() {
var state = "";
for (displayent = 0; displayent < list.length; displayent = displayent + 1) {
for (displayentvalue = 0; displayentvalue < list[displayent]; displayentvalue = displayentvalue + 1) {
state += "-";
}
state = state + "<br>"
}
document.getElementById("output").innerHTML = state;
}
function main() {
// Number of values
var valuecount = document.getElementById("values").value;
// Self-explanatory
var isSorted = false;
alert("working");
// Generate presorted list
list = [0, 1, 2, 3];
display_list();
}
*,
:before,
:after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>The Worst Sorting Algorithm Ever Made</title>
</head>
<body>
<h1>The Worst Sorting Algorithm Ever Made</h1>
<form>
<label for="values">Number of equally spaced values:</label><br>
<input type="number" id="values" name="values"><br><br><br>
<input type="button" id="start" value="Start" onclick="main()"><br><br><br>
</form>
<p id="output"></p>
</body>
</html>
Re Wrote the logic of your code
// I can't believe I have to implement this myself
function randfloat(min, max) {
return Math.random() * (max - min) + min;
}
function randint(min, max) {
return Math.round(randfloat(min, max));
}
// List
var list = [];
// Swap two entries
function swap(value1, value2) {
list[value2] = [list[value1], list[value1] = list[value2]][0];
}
// Shuffle list
function shufflelist() {
list.forEach((element, index) => {
swap(index, randint(0, list.length))
})
}
// Display list
function display_list() {
var state = "";
list.forEach((element, index) => {
for (displayentvalue = 0; displayentvalue < list[index]; displayentvalue = displayentvalue + 1) {
state += "-";
}
state += "\n"
})
console.log(state);
}
function main() {
// Number of values
var valuecount = document.getElementById("values").value;
// Self-explanatory
var isSorted = false;
alert("working");
// Generate presorted list
list = [0, 1, 2, 3];
display_list();
shufflelist();
display_list();
}
*,
:before,
:after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>The Worst Sorting Algorithm Ever Made</title>
</head>
<body>
<h1>The Worst Sorting Algorithm Ever Made</h1>
<form>
<label for="values">Number of equally spaced values:</label><br>
<input type="number" id="values" name="values"><br><br><br>
<input type="button" id="start" value="Start" onclick="main()"><br><br><br>
</form>
<p id="output"></p>
</body>
</html>

how to continually add to a price total in a shopping list

i'm trying to write a program that keeps adding to the current total price displayed as the user keeps inputting/adding more items in the text box area. The code i wrote currently resets the price every time a user inputs/adds an item into the text box. Please how can i solve this problem. I need items and price added to the text box to be added to the current amkunt displayed and not start from the beginning.
function getPrice(itemField) {
return itemField.value || 0;
}
function updateItemfield(itemField) {
var item = getPrice(itemField);
if (getPrice(itemField)) {
itemField.value = item;
} else {
itemField.value = itemField.defaultValue;
}
}
function displayItems(disp, goods) {
hide(disp);
if (goods != 0) {
show(disp);
disp.innerHTML = goods;
}
}
function getQuantity(quantityField) {
return parseInt(quantityField.value, 10) || 0;
}
function updateItemQuantity(itemField, quantityField) {
var quantity = getQuantity(quantityField);
if (quantity < 1) {
quantity = 1;
}
if (getPrice(itemField)) {
quantityField.value = quantity;
} else {
quantityField.value = quantityField.defaultValue;
}
}
function getItemTotal(itemField, quantityField) {
return getPrice(itemField) * getQuantity(quantityField);
}
function hide(el) {
el.className = 'hidden';
}
function show(el) {
el.className = '';
}
function updateTotal(el, amount) {
hide(el);
if (amount > 0) {
show(el);
el.innerHTML = "Your Order Total is $" + amount;
}
}
function forEachFormItem(form, items, func) {
var i,
item,
itemField,
quantityField,
result = 0;
for (i = 0; i < items.length; i += 1) {
item = items[i];
itemField = form.elements[item],
quantityField = form.elements[item + 'quantity'],
result += func(itemField, quantityField);
}
return result;
}
// function addRecord() {
// var inp = document.getElementById('inputtext');
// quotes.push(inp.value);
// inp.value = "";
// }
function calculateTotal() {
var form = this,
items = ['wine'],
total = 0,
priceField = form.priceField;
forEachFormItem(form, items, updateItemQuantity);
total = forEachFormItem(form, items, getItemTotal);
updateTotal(priceField, total);
}
var goods = [];
function addItems() {
var inp = document.getElementById('inputtext');
goods.push(inp.value);
inp.value = "";
}
function newItem() {
document.getElementById("itemDisplay").innerHTML = goods.join(", ");
}
var theForm = document.getElementById('order');
theForm.priceField = document.getElementById('totalPrice');
theForm.onchange = calculateTotal;
.hidden {
display: none;
}
<form id="order" method="post" action="mailto:seyicole#gmail.com">
<fieldset id="selections">
<legend><strong>Your Selections</strong></legend>
<img class="wine" src="wine.png" alt="Select Your Items!!">
<p>
<label>Wine:</label>
<input type="text" name="" id="inputtext" placeholder="item">
<input type="text" name="wine" value="0" size="8">
<input type="text" name="winequantity" value="Quantity" size="8">
<button type="button" id="add" onclick="addItems(), newItem()";>Add </button>
</p>
</fieldset>
<h1>Items</h1>
<div id="itemDisplay">
</div>
<br>
<input type="submit" value="Place order">
</form>
<div id="totalPrice"></div>
The problem is that you are not storing the entered goods anywhere, you are just storing the names.
I recommend that instead of just storing the name, you store an object containing added goods, along with the total amount.
function getPrice(itemField) {
return itemField.value || 0;
}
function updateItemfield(itemField) {
var item = getPrice(itemField);
if (getPrice(itemField)) {
itemField.value = item;
} else {
itemField.value = itemField.defaultValue;
}
}
function displayItems(disp, goods) {
hide(disp);
if (goods != 0) {
show(disp);
disp.innerHTML = goods;
}
}
function getQuantity(quantityField) {
return parseInt(quantityField.value, 10) || 0;
}
function updateItemQuantity(itemField, quantityField) {
var quantity = getQuantity(quantityField);
if (quantity < 1) {
quantity = 1;
}
if (getPrice(itemField)) {
quantityField.value = quantity;
} else {
quantityField.value = quantityField.defaultValue;
}
}
function getItemTotal(itemField, quantityField) {
return getPrice(itemField) * getQuantity(quantityField);
}
function hide(el) {
el.className = 'hidden';
}
function show(el) {
el.className = '';
}
function updateTotal(el, amount) {
hide(el);
if (amount > 0) {
show(el);
el.innerHTML = "Your Order Total is $" + amount;
}
}
function forEachFormItem(form, items, func) {
var i,
item,
itemField,
quantityField,
result = 0;
for (i = 0; i < items.length; i += 1) {
item = items[i];
itemField = form.elements[item],
quantityField = form.elements[item + 'quantity'],
result += func(itemField, quantityField);
}
return result;
}
// function addRecord() {
// var inp = document.getElementById('inputtext');
// quotes.push(inp.value);
// inp.value = "";
// }
function calculateTotal() {
var form = this,
items = ['wine'],
total = 0,
priceField = form.priceField;
// Get total goods and update total
total = goods.reduce((a, c) => a + c.total, 0);
updateTotal(totalPrice, total);
}
var goods = [];
function addItems() {
var inp = document.getElementById('inputtext');
// Calculate total price
const itemField = theForm.elements['wine'];
const quantityField = theForm.elements['winequantity'];
const total = getItemTotal(itemField, quantityField);
// Store name and total price
goods.push({name: inp.value, total});
inp.value = "";
}
function newItem() {
document.getElementById("itemDisplay").innerHTML = goods.map(x => x.name).join(", ");
}
var theForm = document.getElementById('order');
theForm.priceField = document.getElementById('totalPrice');
.hidden {
display: none;
}
<form id="order" method="post" action="mailto:seyicole#gmail.com">
<fieldset id="selections">
<legend><strong>Your Selections</strong></legend>
<img class="wine" src="wine.png" alt="Select Your Items!!">
<p>
<label>Wine:</label>
<input type="text" name="" id="inputtext" placeholder="item">
<input type="text" name="wine" value="0" size="8">
<input type="text" name="winequantity" placeholder="Quantity" size="8">
<button type="button" id="add" onclick="addItems(), newItem(), calculateTotal()" ;>Add </button>
</p>
</fieldset>
<h1>Items</h1>
<div id="itemDisplay">
</div>
<br>
<input type="submit" value="Place order">
</form>
<div id="totalPrice"></div>

Add space after dot

Good day. I've got some problem.
I've got input where I wrote some information.
Example:
<div class="wizard wizardstep1" ng-controller='someCtrl'>
<p class="wizardtitle">Put you Theme</p>
<input id="taskTheme" required type="text" placeholder="Put you Theme" ng-model="taskThemeWizardInputValue" ng-change="checkThemeWizardInputValue()">
</div>
And I've got my controller.
Example:
$scope.checkThemeWizardInputValue = function () {
if ($scope.taskThemeWizardInputValue === undefined) {
$scope.taskThemeWizardInputValue = "";
console.log($scope.taskThemeWizardInputValue);
console.log($scope.taskThemeWizardInputValue.length);
} else {
var strt = $scope.taskThemeWizardInputValue.split('.');
for (var i = 0 ; i < strt.length; i++) {
strt[i] = strt[i].charAt(0).toUpperCase() + strt[i].substr(1);
}
$scope.taskThemeWizardInputValue = strt.join('.');
console.log($scope.taskThemeWizardInputValue);
console.log(strt);
}
}
How I can add space after dot? Who knows?
Here is link to jsfiddle with my example.
We achieve it by adding space to each splitted string other than first one and an empty string
function someCtrl($scope) {
$scope.checkThemeWizardInputValue = function () {
if ($scope.taskThemeWizardInputValue === undefined) {
$scope.taskThemeWizardInputValue = "";
console.log($scope.taskThemeWizardInputValue);
console.log($scope.taskThemeWizardInputValue.length);
} else {
var strt = $scope.taskThemeWizardInputValue.split('.');
for (var i = 0 ; i < strt.length; i++) {
var addSpace='';
if(i>0 && strt[i].trim().length>0){
addSpace=' ';
}
strt[i] = addSpace+strt[i].trim().charAt(0).toUpperCase() + strt[i].trim().substr(1);
}
$scope.taskThemeWizardInputValue = strt.join('.');
console.log($scope.taskThemeWizardInputValue);
console.log(strt);
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
<div class="wizard wizardstep1" ng-controller='someCtrl'>
<p class="wizardtitle">Put you Theme</p>
<input id="taskTheme" required type="text" placeholder="Put you Theme" ng-model="taskThemeWizardInputValue" ng-change="checkThemeWizardInputValue()">
</div>
</div>
You can do this simply by changing strt.join('.') to strt.join('. ').
$scope.checkThemeWizardInputValue = function () {
if ($scope.taskThemeWizardInputValue === undefined) {
$scope.taskThemeWizardInputValue = "";
console.log($scope.taskThemeWizardInputValue);
console.log($scope.taskThemeWizardInputValue.length);
} else {
var strt = $scope.taskThemeWizardInputValue.split('.');
for (var i = 0 ; i < strt.length; i++) {
strt[i] = strt[i].trim();
if(strt[i].length > 0) {
strt[i] = ' '+strt[i].charAt(0).toUpperCase() + strt[i].substr(1);
}
}
$scope.taskThemeWizardInputValue = strt.join('.');
console.log($scope.taskThemeWizardInputValue);
console.log(strt);
}
}
This is working fiddle
I suggest creating a directive so that you can plugin this behaviour whenever required., rather than writing your ng-change in every controller.
In directive simple line element.val(event.target.value.split(".").join(". ")); will work for you., with help of directive controller parameter.
See example fiddle

How to add a variable's value to an array function?

I'm trying to add the random number to the array which is assigned to a function that keeps adding the numbers together.
function getMiNumber(number){
var value = Math.floor(Math.random() * 10) + 1 ;
value.push(value.value);
var myArray = someCalc([0]);
console.log(myArray);
function showMe(val) {
var presentMe = document.getElementById('someId');
presentMe.innerHTML = val;
}
showMe(myArray);
function someCalc(list) {
var total = 0;
for(var i = 0; i < list.length; i++){
total += list[i];
}
return total;
}
}
UPDATE
Reread the question and determined that a cumulative total is desired so this demo will:
Generate a random number 1 to 10.
Display that number.
Add that number to an array.
Display that array.
Add all of the array's elements.
Display that total.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>34562147</title>
<style>
html,
body {
font: small-caps 400 16px/1.4 'Source Code Pro';
}
fieldset {
border: 2px inset grey;
border-radius: 10px;
}
legend {
font-size: 1.3rem;
}
</style>
</head>
<body>
<fieldset>
<legend>Random Array Total</legend>
<input id="btn1" type="button" onclick="rand()" value="Random" />
<br/>
<label for="out0">Next:
<output id="out0"></output>
</label>
<br/>
<label for="out1">Array:
<output id="out1"></output>
</label>
<br/>
<label for="out2">Total:
<output id="out2"></output>
</label>
</fieldset>
<script>
var xArray = [];
function rand() {
var ran1 = Math.floor(Math.random() * 10) + 1;
var out0 = document.getElementById('out0');
var out1 = document.getElementById('out1');
var out2 = document.getElementById('out2');
out0.value = ran1;
xArray.push(ran1);
out1.value = xArray;
out2.value = calc(xArray);
}
function calc(xArray) {
var total = 0;
for (var i = 0; i < xArray.length; i++) {
total += xArray[i];
}
return total;
}
</script>
</body>
</html>
OLD
The array is pre-determined in this demo var xArray = [23, 8, 90, 7];
function randomNumber(xArray){
var value = Math.floor(Math.random() * 10) + 1 ;
xArray.push(value);
return xArray;
}
var xArray = [23, 8, 90, 7];
var total = calc(randomNumber(xArray));
console.log(total);
function output(total) {
var out1 = document.getElementById('out1');
out1.value = total;
}
function calc(list) {
var total = 0;
for(var i = 0; i < list.length; i++){
total += list[i];
}
return total;
}
output(total);
<output id="out1"></output>

Categories

Resources