Calculating items that were entered into an array - javascript

I'm trying to find a way to calculate the data that was entered into an array.
The JavaScript
function getInput()
{
var even = [];
var odd = [];
var num = prompt("Enter your number");
if (num % 2 === 0) {
alert("Data entered into array.");
even.push(num);
}
else if (num % 2 == 1) {
alert("Data entered into array.");
odd.push(num)
}
else {
alert("Invalid input.");
}
}
function finished() //This is where the calculations are done. It's accessed by a button in my HTML.
{
var sum = document.getElementById("leftSumOutput").innerHTML = even[];
}
This is the structure for the page. I'm trying to use tables to store the outputs.
The HTML
<!DOCTYPE html>
<html>
<head>
<title>Sample Title</title>
<script type="text/javascript" src="assignmentOne.js"></script>
<link rel="stylesheet" type="text/css" href="assignmentOne.css">
<link rel="icon" href="favicon.png" type="image/x-icon" />
</head>
<body>
<div align=center>
<h1>Welcome to Assignment One!</h1>
<label for="input">Click for each time you would like to make an input ==></label>
<button id="input" onclick="getInput()"><b>Click to input data</b></button><br><br>
<button id="done" onclick="finished()">Click here when done</button>
<!--<h1 id="even">Even</h1>
<h1 id="odd">Odd</h1>
<p id="left"></p>
<p id="right"></p>
<p id="leftResult"></p>
<p id="rightResult"></p>-->
<table>
<tr>
<th></th>
<th>Even</th>
<th>Odd</th>
</tr>
<tr>
<td></td>
<td id="even"></td>
<td id="odd"></td>
</tr>
<tr colspan="2">
<td>Sum</td>
<td id="leftSumOutput"></td>
<td id="rightSumOutput"></td>
</tr>
<tr colspan="2">
<td>Average</td>
<td id="leftAvgOutput"></td>
<td id="rightAvgOutput"></td>
</tr>
</table>
</div>
</body>
</html>
I want to calculate the items within the array. I'm a novice, so I apologize in advance.
EDIT: I forgot to mention that I don't know how to calculate the averages of the fields either. Any help with that would be appreciated. Thanks everyone for your assistance so far!

I think you are little bit confused with scoping of variables.
Here is an example of how it could've been done:
(function(w, d) {
var odds = [], evens = [], button, elSumOdds,elSumEvens, elAvgOdds, elAvgEvens, s
w.addEventListener('load', function() {
button = d.querySelector('button')
elSumOdds = d.querySelector('#sum-odds')
elSumEvens = d.querySelector('#sum-evens')
elAvgOdds = d.querySelector('#avg-odds')
elAvgEvens = d.querySelector('#avg-evens')
button.addEventListener('click', calculate)
})
function calculate() {
var i = prompt('enter number') | 0;
if ((i|0)%2) {
odds.push(i)
s = odds.reduce(function(a,n) { return a+n }, 0)
elSumOdds.innerText = s
elAvgOdds.innerText = s / odds.length
} else {
evens.push(i)
s = evens.reduce(function(a,n) { return a+n }, 0)
elSumEvens.innerText = s
elAvgEvens.innerText = s / evens.length
}
}
})(window, document)
<button > calculate</button>
<table>
<tr><td></td><td>Sum</td><td>Avg</td></tr>
<tr><td>Odds</td><td id='sum-odds'></td><td id='avg-odds'></td></tr>
<tr><td>Evens</td><td id='sum-evens'></td><td id='avg-evens'></td></tr>
</table>

If you need to calculate sum of each element in array you need to write map function. Visit link: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map
if you just need to know amount of elements, call: alert(even.length);

Note: #vittore 's structure inspired this change.
(function(d) {
d.getElementById('input').addEventListener('click', getInput);
d.getElementById('done').addEventListener('click', finished);
var elSumOdd = d.getElementById('oddSumOutput');
var elSumEven = d.getElementById('evenSumOutput');
var elAvgOdd = d.getElementById('oddAvgOutput');
var elAvgEven = d.getElementById('evenAvgOutput');
var even = [];
var odd = [];
function getInput() {
var num = prompt("Enter your number") | 0;
if (num % 2 == 0) {
even.push(num);
} else if (num % 2 == 1) {
odd.push(num);
} else {
alert("Invalid input.");
}
finished();
}
function finished() { //This is where the calculations are done. It's accessed by a button in my HTML.
elSumOdd.innerHTML = odd.reduce(function(a, b) {
return a + b;
}, 0);
elSumEven.innerHTML = even.reduce(function(a, b) {
return a + b;
}, 0);
elAvgOdd.innerHTML = elSumOdd.innerHTML / odd.length || 0;
elAvgEven.innerHTML = elSumEven.innerHTML / even.length || 0;
}
})(document);
<div align=center>
<h1>Welcome to Assignment One!</h1>
<label for="input">Click for each time you would like to make an input ==></label>
<button id="input"><b>Click to input data</b>
</button>
<br>
<br>
<button id="done">Click here when done</button>
<!--<h1 id="even">Even</h1>
<h1 id="odd">Odd</h1>
<p id="left"></p>
<p id="right"></p>
<p id="leftResult"></p>
<p id="rightResult"></p>-->
<table>
<tr>
<th></th>
<th>Even</th>
<th>Odd</th>
</tr>
<tr>
<td></td>
<td id="even"></td>
<td id="odd"></td>
</tr>
<tr colspan="2">
<td>Sum</td>
<td id="evenSumOutput"></td>
<td id="oddSumOutput"></td>
</tr>
<tr colspan="2">
<td>Average</td>
<td id="evenAvgOutput"></td>
<td id="oddAvgOutput"></td>
</tr>
</table>
</div>

Related

Why is the page instantly reloading on clicking the 'form-on submit' button? [duplicate]

This question already has answers here:
How to prevent form from being submitted?
(11 answers)
Closed 3 months ago.
I want to create a page that displays a message when the user gives input. But the moment I click on the button to display the message the page instantly reloads and clears out the page:
HTML Code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Fibonacci Series</title>
</head>
<body>
<form onsubmit="return getFibonacci()">
<table>
<tr>
<td>Enter the number to get a fibonacci</td>
<td><input type="number" id="fibo" name="fibo" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" id="fibobtn" name="fibobtn" value="Get Fibonacci" /></td>
</tr>
</table>
<div id="result"></div>
</form>
<script src="script.js"></script>
</body>
</html>
JavaScript Code:
function getFibonacci() {
try {
var num = document.getElementById("fibo").value;
var fib0 = 0;
var fib1 = 1;
var next;
const fib = [];
for (var i = 0; i < num - 1; i++) {
next = fib0 + fib1;
fib0 = fib1;
fib1 = next;
fib.push(fib0)
document.getElementById("result").innerHTML = fib;
}
}
catch (err) {
document.getElementById("result").innerHTML = err;
}
}
Prevent that by adding event.preventDefault. Also you need to convert the value of the input to number which is done by adding unary operator +document.getElementById("fibo").value;. You can also use parseInt
function getFibonacci(event) {
event.preventDefault()
try {
var num = +document.getElementById("fibo").value;
var fib0 = 0;
var fib1 = 1;
var next;
const fib = [];
for (var i = 0; i < num - 1; i++) {
next = fib0 + fib1;
fib0 = fib1;
fib1 = next;
fib.push(fib0)
document.getElementById("result").innerHTML = fib;
}
} catch (err) {
document.getElementById("result").innerHTML = err;
}
}
<form onsubmit="return getFibonacci(event)">
<table>
<tr>
<td>Enter the number to get a fibonacci</td>
<td><input type="number" id="fibo" name="fibo" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" id="fibobtn" name="fibobtn" value="Get Fibonacci" /></td>
</tr>
</table>
<div id="result"></div>
</form>
It is reloading because the default behaviour of submit handlers is to reload the page. To avoid this we have stop this by using event.preventDefault().
Try the below changes:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Fibonacci Series</title>
</head>
<body>
<form onsubmit="return getFibonacci(event)">
<table>
<tr>
<td>Enter the number to get a fibonacci</td>
<td><input type="number" id="fibo" name="fibo" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" id="fibobtn" name="fibobtn" value="Get Fibonacci" /></td>
</tr>
</table>
<div id="result"></div>
</form>
<script src="script.js"></script>
</body>
</html>
function getFibonacci(event) {
event.preventDefault()
try {
var num = document.getElementById("fibo").value;
var fib0 = 0;
var fib1 = 1;
var next;
const fib = [];
for (var i = 0; i < num - 1; i++) {
next = fib0 + fib1;
fib0 = fib1;
fib1 = next;
fib.push(fib0)
document.getElementById("result").innerHTML = fib;
}
}
catch (err) {
document.getElementById("result").innerHTML = err;
}
}

How do I count checked checkboxes in list.js that are not currently displayed?

I have a table with checkboxes in list.js. I want to count all checkboxes that are checked, even those hidden due to the search function of the list. The method below works for only the checkboxes that are currently displayed after searching.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Counting checked checkboxes</title>
</head>
<script src="//cdnjs.cloudflare.com/ajax/libs/list.js/1.5.0/list.min.js"></script>
<body>
<div id='sample_rows'>
<div id='sample_count'></div>
<input class="search" placeholder="Search" />
<table>
<tbody class="list">
<tr>
<td class='name'>checkbox1</td>
<td class="checked">
<input class="sample_checkbox" type="checkbox" name="checkbox1" id="checkbox1" onclick="update_count()">
</td>
</tr>
<tr>
<td class='name'>checkbox2</td>
<td class="checked">
<input class="sample_checkbox" type="checkbox" name="checkbox2" id="checkbox2" onclick="update_count()">
</td>
</tr>
</tbody>
</table>
</div>
<script>
var list_options = {
valueNames: ['name', 'checked'],
searchDelay: 500
};
var sample_list = new List('sample_rows', list_options);
sample_list.on('updated', update_count);
document.addEventListener("load", update_count());
function update_count(){
let total = sample_list.size();
let checked_count = 0;
let items = sample_list.items;
for (let i = 0; i < total; i++){
let item = items[i];
let checkbox_id = items[i]._values['name'];
let sample_checkbox = document.getElementById(checkbox_id);
if(sample_checkbox != null){
if (sample_checkbox.checked){
checked_count += 1;
}
}
else {
alert('Cannot find state of ' + checkbox_id);
}
}
document.getElementById('sample_count').innerHTML = String(checked_count) + " selected";
}
</script>
</body>
</html>
The state of checkboxes is preserved while searching, so the count should be available. This is illustrated by:
Check both checkboxes. Count is 2.
Search for "box2". Count is displayed as 1, with alert for the box that fails to get counted.
Clear search box. Count is 2 again because state of undisplayed checkbox is preserved.
How can I count all of the checked checkboxes when a search has been applied?
This code will keep your checked count intact whether your checkboxes are hidden or not
<!DOCTYPE html>
<html lang="en">
<head>
<title>Counting checked checkboxes</title>
</head>
<script src="//cdnjs.cloudflare.com/ajax/libs/list.js/1.5.0/list.min.js"></script>
<body>
<div id='sample_rows'>
<div id='sample_count'></div>
<input class="search" placeholder="Search" />
<table>
<tbody class="list">
<tr>
<td class='name'>checkbox1</td>
<td class="checked">
<input class="sample_checkbox" type="checkbox" name="checkbox1" id="checkbox1" onclick="update_count('checkbox1')">
</td>
</tr>
<tr>
<td class='name'>checkbox2</td>
<td class="checked">
<input class="sample_checkbox" type="checkbox" name="checkbox2" id="checkbox2" onclick="update_count('checkbox2')">
</td>
</tr>
</tbody>
</table>
</div>
<script>
var checked_count = 0;
var list_options = {
valueNames: ['name', 'checked'],
searchDelay: 500
};
var sample_list = new List('sample_rows', list_options);
sample_list.on('updated', update_count);
document.addEventListener("load", update_count_on_load());
function update_count_on_load() {
let total = sample_list.size();
let checked_count = 0;
let items = sample_list.items;
for (let i = 0; i < total; i++) {
let item = items[i];
let checkbox_id = items[i]._values['name'];
let sample_checkbox = document.getElementById(checkbox_id);
if (sample_checkbox != null) {
if (sample_checkbox.checked) {
checked_count += 1;
}
} else {
alert('Cannot find state of ' + checkbox_id);
}
}
document.getElementById('sample_count').innerHTML = String(checked_count) + " selected";
}
function update_count(checkbox_id) {
let sample_checkbox = document.getElementById(checkbox_id);
if (sample_checkbox) {
if (sample_checkbox.checked) {
checked_count += 1;
} else {
checked_count -= 1;
}
}
document.getElementById('sample_count').innerHTML = checked_count + " selected";
}
</script>
</body>
</html>
I just wrote you a new logic for calculation:
do your count based on click, no need use list if im not mistaken for some reason, and save result in variable.
...
let res = 0
document.querySelectorAll("input[type=checkbox]").forEach(input => {
input.addEventListener("click", (e) => {
e.target.checked ? res = res + 1 : res = res - 1
document.getElementById('sample_count').innerHTML = res + " selected";
})
})
...
remove
document.getElementById('sample_count').innerHTML
from your function. To be fair not sure whats going on there, looks a bit to much for simple calculation.
let res = 0
document.querySelectorAll("input[type=checkbox]").forEach(input => {
input.addEventListener("click", (e) => {
e.target.checked ? res = res + 1 : res = res - 1
document.getElementById('sample_count').innerHTML = res + " selected";
})
})
<!DOCTYPE html>
<html lang="en">
<head>
<title>Counting checked checkboxes</title>
</head>
<script src="//cdnjs.cloudflare.com/ajax/libs/list.js/1.5.0/list.min.js"></script>
<body>
<div id='sample_rows'>
<div id='sample_count'></div>
<input class="search" placeholder="Search" />
<table>
<tbody class="list">
<tr>
<td class='name'>checkbox1</td>
<td class="checked">
<input class="sample_checkbox" type="checkbox" name="checkbox1" id="checkbox1" onclick="update_count()">
</td>
</tr>
<tr>
<td class='name'>checkbox2</td>
<td class="checked">
<input class="sample_checkbox" type="checkbox" name="checkbox2" id="checkbox2" onclick="update_count()">
</td>
</tr>
</tbody>
</table>
</div>
<script>
var list_options = {
valueNames: ['name', 'checked'],
searchDelay: 500
};
var sample_list = new List('sample_rows', list_options);
sample_list.on('updated', update_count);
document.addEventListener("load", update_count());
function update_count() {
let total = sample_list.size();
let checked_count = 0;
let items = sample_list.items;
for (let i = 0; i < total; i++) {
let item = items[i];
let checkbox_id = items[i]._values['name'];
let sample_checkbox = document.getElementById(checkbox_id);
if (sample_checkbox != null) {
if (sample_checkbox.checked) {
checked_count += 1;
}
} else {
// alert('Cannot find state of ' + checkbox_id);
}
}
//document.getElementById('sample_count').innerHTML = String(checked_count) + " selected";
}
</script>
</body>
</html>

Javascript get id from element and then use it

Can you help me with this problem? I can't use return x value for my other function. I want when I click on some element, then script load ID of clicked element and then change color of element with this ID.
Is there some better solution for my problem? (in pure JS, not in Jquery)
Thanks.
<p id="1">foo</p>
<p id="2">bar</p>
<p id="3">baz</p>
<script>
document.addEventListener('click', function(e) {
x=e.target.id;
return x
});
document.getElementById(x).onclick =
function(x) {
if (document.getElementById(x).style.backgroundColor !== 'yellow') {
document.getElementById(x).style.backgroundColor = 'yellow';
}
else {
document.getElementById(x).style.backgroundColor = 'red';
}
};
</script>
Change your code to below.
<p id="1">foo</p>
<p id="2">bar</p>
<p id="3">baz</p>
document.addEventListener('click', function(e) {
x=e.target.id;
function() {
var bgColor = document.getElementById(x).style.backgroundColor;
if (bgColor !== 'yellow') {
bgColor = 'yellow';
}
else {
bgColor = 'red';
}
}
});
</script>
Ok i find solution on my problem.
The solution was put all my script in one function and than evrything work.
I learning JS about 1 mount and now I have made one simple LIGHTS OFF game.
Now I nedd some function that check all cells color and alert end of game, but i cant answer a new question because by question is not voted well, and i dont know why.
Here is the example of my code:
document.addEventListener('click', function(e) {
var x = e.target.id
var up = ((Math.floor(x.charAt(0))-1).toString()).concat(x.charAt(1));
var down = ((Math.floor(x.charAt(0))+1).toString()).concat(x.charAt(1));
var left = (x.charAt(0)).concat((Math.floor(x.charAt(1))-1).toString());
var right = (x.charAt(0)).concat((Math.floor(x.charAt(1))+1).toString());
if( document.getElementById(x).style.backgroundColor == ''){document.getElementById(x).style.backgroundColor = 'black';}
else{document.getElementById(x).style.backgroundColor ='';}
if(document.getElementById(up)!=null){
if( document.getElementById(up).style.backgroundColor == ''){document.getElementById(up).style.backgroundColor = 'black';}
else{document.getElementById(up).style.backgroundColor ='';}}
if(document.getElementById(down)!=null){
if( document.getElementById(down).style.backgroundColor == ''){document.getElementById(down).style.backgroundColor = 'black';}
else{document.getElementById(down).style.backgroundColor ='';}}
if(document.getElementById(left)!=null){
if( document.getElementById(left).style.backgroundColor == ''){document.getElementById(left).style.backgroundColor = 'black';}
else{document.getElementById(left).style.backgroundColor ='';}}
if(document.getElementById(right)!=null){
if( document.getElementById(right).style.backgroundColor == ''){document.getElementById(right).style.backgroundColor = 'black';}
else{document.getElementById(right).style.backgroundColor ='';}}
// var all = document.getElementsByTagName("TD");
// var i;
// for (i = 0; i < all.length; i++) {
// all[i].style.backgroundColor!=='yellow';
// alert('a')
// break}
})
td {
padding: 50px;
background-color: yellow;
<table>
<tr>
<td id='11'></td>
<td id='12'></td>
<td id='13'></td>
<td id='14'></td>
<td id='15'></td>
</tr>
<tr>
<td id='21'></td>
<td id='22'></td>
<td id='23'></td>
<td id='24'></td>
<td id='25'></td>
</tr>
<tr>
<td id='31'></td>
<td id='32'></td>
<td id='33'></td>
<td id='34'></td>
<td id='35'></td>
</tr>
<tr>
<td id='41'></td>
<td id='42'></td>
<td id='43'></td>
<td id='44'></td>
<td id='45'></td>
</tr>
<tr>
<td id='51'></td>
<td id='52'></td>
<td id='53'></td>
<td id='54'></td>
<td id='55'></td>
</tr>
</table>

Javascript writing into Table not working

I just decided to code a little html file which should create a multiplication table with integers from "start" to "end". Start and End are set before in a HTMl Form...
I can give 2 numbers as input and the tr and td elements are create but accessing them by ClassName and filling them with innerHTML does somehow not work.
Here is the Code:
<html>
<head>
<title>Das groà ¥ 1x1</title>
<meta charset="utf-8">
</head>
<script type="text/javascript">
function malnehmen(Wert1, Wert2) {
Ausgabe = Wert1 * Wert2;
return Ausgabe;
}
function tabelle() {
var start = document.forms["printer"].anfang.value;
var end = document.forms["printer"].ende.value;
for(i = start; i < end+1; i++) {
Reihe = document.createElement("tr");
att = document.createAttribute("class");
att.value = i + "a";
Reihe.setAttributeNode(att);
document.getElementById("Darein").appendChild(Reihe);
for(ii = start; ii < end+1; ii++) {
Feld = document.createElement("td");
att2 = document.createAttribute("class");
att2.value = malnehmen(i, ii);
Feld.setAttributeNode(att2);
Reihe.appendChild(Feld);
}
}
}
function ausfuellen() {
tabelle();
var start = document.forms["printer"].anfang.value;
var end = document.forms["printer"].ende.value;
for(a = start; a < end+1; a++) {
alert("Hier denn?");
document.getElementsByClassName(a + "a").innerHTML = a.toString();
for(aa = start; aa < end+1; aa++) {
multi = malnehmen(a, aa);
alert("Angekommen");
document.getElementsByClassName(multi).innerHTML = multi.toString();
}
}
}
</script>
<body>
<FORM name="printer">
<TABLE>
<tr>
<td>Beginnt bei:</td>
<td>
<input type="number" name="anfang" size="3">
</td>
</tr>
<tr>
<td>Endet bei:</td>
<td>
<input type="number" name="ende" size="3">
</td>
</tr>
<tr>
<td>
<input type="button" name="wassolldas" value="Erstellen" onclick="javascript: tabelle();">
</td>
</tr>
</TABLE>
</FORM>
<br>
<TABLE id="Darein" border="1">
</TABLE>
</body>
Does anybody know what I did wrong?
I built in 2 alerts just to see if the javascript part reaches the for loop but there is no pop up in browser.

Validating Empty Squares TicTacToe - Javascript only

First I would like to say thank you to the individuals that helped me with this question before. For the ones that decided to close my post without even trying to first assist me, please refrain from closing my post if you are not deciding to help and calling my issue too broad. Also, I'm not looking as of this time to "optimize" my code or for corrections with how I expatiate my summary below. Now, for the real issue...
I'm trying my hand at building a tic-tac-toe game with plain vanilla Javascript, so I'm hoping we can stay in the boundaries of keeping it simple Javascript. Do not optimize code!
What I require is the following: I need code that will check each square to see if it's filled with an X or an O. If squares are still available, no need for an alert but if all squares are filled, I need it to alert me "No more moves!"
I have started the function checkEmpty
Thank you for your assistance and time!
Here is the code I have got so far:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Tic Tac Toe</title>
<style>
td {
border: 1px solid black;
height: 250px;
width: 250px;
font-family: sans-serif;
font-size: 150pt;
text-transform: uppercase;
}
</style>
</head>
<body>
<table>
<tr>
<td align="center" id="square1" onclick="displayMarker('square1');"></td>
<td align="center" id="square2" onclick="displayMarker('square2');"></td>
<td align="center" id="square3" onclick="displayMarker('square3');"></td>
</tr>
<tr>
<td align="center" id="square4" onclick="displayMarker('square4');"></td>
<td align="center" id="square5" onclick="displayMarker('square5');"></td>
<td align="center" id="square6" onclick="displayMarker('square6');"></td>
</tr>
<tr>
<td align="center" id="square7" onclick="displayMarker('square7');"></td>
<td align="center" id="square8" onclick="displayMarker('square8');"></td>
<td align="center" id="square9" onclick="displayMarker('square9');"></td>
</tr>
</table>
<script>
var cp1 = 1;
function displayMarker(allSquares) {
if (document.getElementById(allSquares).innerHTML != "") {
alert("Choose another square");
}
else {
if (cp1 == 1) {
document.getElementById(allSquares).innerHTML = "X";
cp1 = 2;
}
else {
document.getElementById(allSquares).innerHTML = "O";
cp1 = 1;
}
}
checkEmpty();
}
function checkEmpty() {
for (var i = 1; i <= 9; i++) {
console.log(document.getElementById('square' + i).innerHTML + " square" + i);
}
</script>
</body>
</html>
Should work:
function checkEmpty() {
for (var i = 1; i <= 9; i++) {
if (!document.getElementById('square' + i).innerHTML) return;
}
alert("all squares filled");
}
function checkEmpty() {
var isEmpty = false;
for (var i = 1; i <= 9; i++) {
var squareVal = document.getElementById('square' + i).innerHTML;
if(squareVal.length == 0)
{
isEmpty = true;
break;
}
}
if(!isEmpty)
{
alert('No more moves');
}
}

Categories