Why does my code sometimes return undefined - javascript

I am trying to display two numbers that are not the same but every time they turn out to be the same and sometimes it displays undefined. Is there any way to fix this?
var usedCard = [0];
var columnB = Math.floor(Math.random()*16);
function columnBB(){
if (usedCard.includes(columnB)){
columnB = Math.floor(Math.random()*16);
columnBB();
}
else {return columnB};
}
document.getElementById("B1").innerHTML = columnBB();
usedCard.push(columnB);
columnB = Math.floor(Math.random()*16)
document.getElementById("B2").innerHTML = columnBB();
<!DOCTYPE html>
<html>
<body>
<table>
<tr>
<td id="B1"></td>
<td id="B2"></td>
</tr>
</table>
</body>
</html>

You are using recursion. When the function calls itself it never returns because it will only call the else branch if the if branch is never called. Remove the else and simply return and you should be good.
var usedCard = [0];
var columnB = Math.floor(Math.random()*16);
function columnBB(){
if (usedCard.includes(columnB)){
columnB = Math.floor(Math.random()*16);
columnBB();
}
return columnB;
}
document.getElementById("B1").innerHTML = columnBB();
usedCard.push(columnB);
columnB = Math.floor(Math.random()*16)
document.getElementById("B2").innerHTML = columnBB();
<!DOCTYPE html>
<html>
<body>
<table>
<tr>
<td id="B1"></td>
<td id="B2"></td>
</tr>
</table>
</body>
</html>

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

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.

Calculating items that were entered into an array

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>

Need help sum of numbers in the row javascript [duplicate]

This question already has answers here:
How to add two strings as if they were numbers? [duplicate]
(20 answers)
Closed 7 years ago.
<html>
<script>
function myFunction() {
var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
var c = document.getElementById("c").value;
var d = document.getElementById("d").value;
var erg = document.getElementById("erg").value;
var sum = a + b + c + d;
document.getElementById("erg").innerHTML = sum;
</script>
<body>
<table border="1">
<tr>
<td id="a">2</td>
<td id="b">4</td>
<td id="c">5</td>
<td id="d">3</td>
<td id="erg"></td>
<td>
<button type="button" onclick="myFunction()">Sum</button>
</td>
</tr>
</table>
</body>
</html>
parse int the number,
and td not has value, use innertext
<html>
<script>
function myFunction() {
var a =parseInt(document.getElementById("a").innerText);
var b = parseInt(document.getElementById("b").innerText);
var c = parseInt(document.getElementById("c").innerText);
var d = parseInt(document.getElementById("d").innerText);
var sum = a + b + c + d;
document.getElementById("erg").innerHTML = sum;
}
</script>
<body>
<table border="1">
<tr>
<td id="a">2</td>
<td id="b">4</td>
<td id="c">5</td>
<td id="d">3</td>
<td id="erg"></td>
<td>
<button type="button" onclick="myFunction()">Sum</button>
</td>
</tr>
</table>
</body>
</html>

How to switch between players in a Javascript tic tac toe game

I'm still a newbie in JS, would appreciate the help and any sort of explanations. So here I go; I don't have the slightest clue why my following code is not switching between "X"s and "O"s each time one of the two players clicks on whatever case they want. One thing is for sure something is wrong with the logic of my if statements.
My html is as follows:
<!DOCTYPE html>
<html>
<head>
<title>Tic Tac Toe</title>
<script text="javascript" src="tic.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<center>
<body>
<h1 style="font-family:arial;">Tic-Tac-Toe</h1>
<table>
<tr>
<td id = "case1" onclick="display_input('case1')"></td>
<td id = "case2" onclick="display_input('case2')"></td>
<td id = "case3" onclick="display_input('case3')"></td>
</tr>
<tr>
<td id = "case4" onclick="display_input('case4')"></td>
<td id = "case5" onclick="display_input('case5')"></td>
<td id = "case6" onclick="display_input('case6')"></td>
</tr>
<tr>
<td id = "case7" onclick="display_input('case7')"></td>
<td id = "case8" onclick="display_input('case8')"></td>
<td id = "case9" onclick="display_input('case9')"></td>
</tr>
</table>
<footer>
<p>Copyright© 2014</p>
</footer>
</body>
</center>
</html>
Javascript:
function display_input(square){
var player_one = 1;
if ( player_one == 1 ){
document.getElementById(square).innerHTML = "X";
player_one = 0;
} else {
document.getElementById(square).innerHTML = "O";
player_one = 1;
}
}
On every call of display_input, you intialise a new player_one variable with the same value: 1. Move the declaration outside of the function, so that subsequent calls will actually toggle the (one) higher-scoped variable:
var player_one = 1;
function display_input(square){
if ( player_one == 1 ){
document.getElementById(square).innerHTML = "X";
player_one = 0;
} else {
document.getElementById(square).innerHTML = "O";
player_one = 1;
}
}

Categories