Making a table with random colored numbers - javascript

With this html:
<html>
<head>
<meta charset="UTF-8">
<title>Bonoloto</title>
<script src="bonoloto.js"></script>
<style>
table {border-collapse: collapse;}
td{border: 1px solid #000000; text-align: center; width: 6%;}
</style>
</head>
<body>
<script>
tables();
</script>
</body>
</html>
And this javascript:
var counter = 0;
var nr1 = Math.floor(Math.random() * 49 + 1),
nr2 = Math.floor(Math.random() * 49 + 1),
nr3 = Math.floor(Math.random() * 49 + 1),
nr4 = Math.floor(Math.random() * 49 + 1),
nr5 = Math.floor(Math.random() * 49 + 1);
document.write("Numbers: "+nr1+" "+nr2+" "+nr3+" "+nr4+" "+nr5);
function tables(){
document.write("<table>");
for(i = 1; i < 50; i++) {
if(counter == 10) {
counter = 0;
document.write("<tr>");
}
if(i==nr1){
document.write("<td style='background-color: cadetblue'>" + i + "</td>");
}else{
document.write("<td>" + i + "</td>");
}
if(counter == 10) {
counter = 0;
document.write("</tr>");
}
counter++;
}
document.write("</table>");
}
This is the output:
I must highlight all the numbers like 25 is highlighted. Numbers are randomly generated and the aim is to highlight them in the table. I get stuck in here:
if(i==nr1){
document.write("<td style='background-color: cadetblue'>" + i + "</td>");
}else{
document.write("<td>" + i + "</td>");
}
If i place more if statements the table columns will "Multiply". I cant get that condition working properly...

Instead of nrXs, use an array of five random numbers. Then in if, check, if the array contains i. Something like this:
var counter = 0,
randoms = [],
n;
for (n = 0; n < 5; n++) {
randoms.push(Math.floor(Math.random() * 49 + 1));
}
function tables(){
document.write("<table>");
for(var i = 1; i < 50; i++) {
if(counter == 10) {
counter = 0;
document.write("<tr>");
}
if (randoms.indexOf(i) > -1) {
document.write("<td style='background-color: cadetblue'>" + i + "</td>");
} else {
document.write("<td>" + i + "</td>");
}
if (counter == 10) {
counter = 0;
document.write("</tr>");
}
counter++;
}
document.write("</table>");
}
tables();
Notice, that document.write is considered as a bad practice, use some DOM manipulation methods instead. In your case HTMLTableElement Interface seems to be suitable.
You can improve the code, since now it's possible to get doubled random numbers to the array.

Try this:
HTML:
<div id="container"></div>
JQUERY (as you can see makes things much simpler):
var colors=['red','yellow','blue','green'];
var i;
$("#container").append("<table></table>");
var tds="";
for(i=1;i<=50;i++){
if(i%10 == 0){
tds+="<td style='background:"+colors[Math.floor(Math.random()*10)%4]+"'>"+i+"</td>"
$("table").append("<tr>"+tds+"</tr>");
tds="";
}
else{
tds+="<td style='background:"+colors[Math.floor(Math.random()*10)%4]+"'>"+i+"</td>";
}
}
CSS:
table,td{
border:solid 1px;
}
table{
border-collapse:collapse;
}
td{
width:6%;
}
Live FIDDLE.

You can try this:
var counter = 0;
var randomNumbers = [];
for (var i = 0; i <= 5; i++) {
randomNumbers.push( Math.floor(Math.random() * 49 + 1));
};
document.write("Numbers: ");
for (var i = randomNumbers.length - 1; i >= 0; i--) {
document.write(randomNumbers[i]+", ");
};
function tables(){
document.write("<table>");
for(i = 1; i < 50; i++) {
var found = false;
if(counter == 10) {
counter = 0;
document.write("<tr>");
}
for (var j = randomNumbers.length - 1; j >= 0; j--) {
if(i == randomNumbers[j]){
document.write("<td style='background-color: cadetblue'>" + i + "</td>");
found = true;
break;
}
};
if(!found){
document.write("<td>" + i + "</td>");
}
if(counter == 10) {
counter = 0;
document.write("</tr>");
}
counter++;
}
document.write("</table>");
}
tables();

Related

Displaying times table using javascript

As I am new to JavaScript, I am a bit confused of using the for loops in JavaScript. I have tried the times table using the below JavaScript code, but I was unsuccessful in creating the times table for 1 to 9, as displayed in the image.
var display = ""; // The table output HTML
for (i = 1; i <= 9; i++) {
var multiplier = 1;
var result = i * 1;
display += multiplier + " * " + i + " = " + result + "\xa0\xa0\xa0\xa0\xa0\xa0\xa0 " ;
}
document.getElementById("outputDiv").innerHTML = display;
I tried using nested for loops, but it left me with an error
This is where I have done with a single for loop
https://codepen.io/vbudithi/pen/LgEPwx
I tried to get the output in the below form
THANKS IN ADVANCE
Use nested loop with break line. "< br >"
Working example: https://codepen.io/anon/pen/yRyLje
var display = "";
for( i = 1; i < 10; i++){
for (j = i; j < 10; j++) {
display += i + " * " + j + " = " + j * i+ "\xa0\xa0\xa0\xa0\xa0" ;
}
display +="<br>";
}
document.getElementById("outputDiv").innerHTML = display;
just like NicolasB said, wrapping the loop in another loop
var display = ""; // The table output HTML
for(j = 1; j <= 9; j++) {
for (i = j; i <= 9; i++) {
var result = i * j;
display += j + " * " + i + " = " + result + "\xa0\xa0\xa0\xa0\xa0\xa0\xa0 " ;
}
display += "<br>";
}
document.getElementById("outputDiv").innerHTML = display;

<td> appending outside </tr>

I'm working on a table, that displays data from loop and the whole row is being appended. The code is working fine, its just when I inspect element I notice that the <td> is outside <tr>, how can I fix it.
hope you help me.
thanks.
var dataNum = 10;
for (let t = 1; t <= dataNum; t++) {
$('table tbody').append('<tr>');
for (var j = 0; j < 2; j++) {
if (j == 0) {
$('table tbody').append('<td>' + todayDate() + '-' + deci(t) + '</td>');
} else if (j == 1) {
$('table tbody').append('<td>' + (Math.floor(Math.random() * 10000) + 90000) + '</td>');
}
}
$('table tbody').append('</tr>');
}
function todayDate() {
var d = new Date(),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [year, month, day].join('');
}
function deci(number) {
var num = null;
if (number < 10) {
num = '000' + number;
} else if (number > 9 && number < 100) {
num = '00' + number;
} else if (number > 99 && number < 1000) {
num = '0' + number;
} else {
num = number;
}
return num;
}
table th, table td{
width: 150px;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Num</th>
<th>Random</th>
</tr>
</thead>
<tbody></tbody>
</table>
In your code, you are appending tr and td both to tbody. You need to append td to tr
for (let t = 1; t <= dataNum; t++) {
$('table tbody').append('<tr></tr>');
for (var j = 0; j < 2; j++) {
if (j == 0) {
$('table tbody tr:last').append('<td>' + todayDate() + '-' + deci(t) + '</td>');
} else if (j == 1) {
$('table tbody tr:last').append('<td>' + (Math.floor(Math.random() * 10000) + 90000) + '</td>');
}
}
}
Your
$('table tbody').append('<td>'...
is appending tds to the tbody.
Try creating the tr first, appending it to the tbody, and then append tds to the tr:
var dataNum = 10;
for (let t = 1; t <= dataNum; t++) {
const $tr = $('<tr></tr>');
$('table tbody').append($tr);
for (var j = 0; j < 9; j++) {
if (j == 0) {
$tr.append('<td>' + todayDate() + '-' + deci(t) + '</td>');
} else if (j == 1) {
$tr.append('<td>' + (Math.floor(Math.random() * 10000) + 90000) + '</td>');
}
}
}
function todayDate() {
var d = new Date(),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [year, month, day].join('');
}
function deci(number) {
var num = null;
if (number < 10) {
num = '000' + number;
} else if (number > 9 && number < 100) {
num = '00' + number;
} else if (number > 99 && number < 1000) {
num = '0' + number;
} else {
num = number;
}
return num;
}
table th, table td{
width: 150px;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Num</th>
<th>Random</th>
</tr>
</thead>
<tbody></tbody>
</table>
That is because of the following line.
$('table tbody').append('<tr>'); This actually appends the tr into the DOM. So basically, <tr></tr> gets autocompleted since browser is smart and tries to ensure valid HTML DOM structure. What you should ideally do is create a string that stores entire DOM structure you need and append it at the end since DOM manipulations are slow.
var dataNum = 10;
var str='';
for (let t = 1; t <= dataNum; t++) {
str += '<tr>';
for (var j = 0; j < 9; j++) {
if (j == 0) {
str += '<td>' + todayDate() + '-' + deci(t) + '</td>';
} else if (j == 1) {
str+= '<td>' + (Math.floor(Math.random() * 10000) + 90000) + '</td>';
}
}
str += '</tr>';
}
$('table tbody').append(str);
function todayDate() {
var d = new Date(),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [year, month, day].join('');
}
function deci(number) {
var num = null;
if (number < 10) {
num = '000' + number;
} else if (number > 9 && number < 100) {
num = '00' + number;
} else if (number > 99 && number < 1000) {
num = '0' + number;
} else {
num = number;
}
return num;
}
table th, table td{
width: 150px;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Num</th>
<th>Random</th>
</tr>
</thead>
<tbody></tbody>
</table>

How do I assign numbers 10 through 16 a letter in this hex/binary table?

var count = -1;
var countLetter = "";
for (outer = 0; outer < 2; outer++) {
for (inner = 0; inner < 2; inner++) {
for (third = 0; third < 2; third++) {
for (fourth = 0; fourth < 2; fourth++) {
count++;
countLetter = count;
document.write(countLetter + "|" + "" + outer + "" + inner + "" + third + "" + fourth + ".</br>");
}
}
}
}
I attempted to add an if(count)=10{counterLetter="A"} and so on but this didn't work, either broke the code or ended up doing something wacky. Any help appreciated!
According to Number.prototype.toString() you may write:
countLetter = count.toString(16).toUpperCase();
The snippet:
var count = -1;
var countLetter = "";
for (outer = 0; outer < 2; outer++) {
for (inner = 0; inner < 2; inner++) {
for (third = 0; third < 2; third++) {
for (fourth = 0; fourth < 2; fourth++) {
count++;
countLetter = count.toString(16).toUpperCase();
document.write(countLetter + "|" + "" + outer + "" + inner + "" + third + "" + fourth + ".</br>");
}
}
}
}
A shorter version:
for (i = 0; i < 16; i++) {
document.write(i.toString(16).toUpperCase() + "|" + ("000" + i.toString(2)).slice(-4) + ".</br>");
}

Adding a small timer to a Questionnaire

I have made a questionnaire that asks 10 questions, however I would like to add a small timer to show how long the user has taken in seconds. I have looked online for help however I always have some issue with displaying the timer itself.
Here's my program:
<html>
<head>
<title>Best Gaming Quiz Ever!</title>
</head>
<body>
<h1>Gaming Quiz</h1>
We have made 10 questions for you to answer about gaming and gaming companies. Do your best, and don't guess,
<br>it's really not that difficult. Also, try not to be a cheating noob and click "check answer" before you make your choice!
<br>Challenge yourself, and have fun!
<h2>Your mission:</h2>
Just pick the correct answer, duh, it's a quiz, what else?
<br>
<br>
<script type="text/javascript">
var allowPeeking = 1
var allowDoOvers = 1
questions = new Array();
// Q & A questions set as Arrays below
// Questions are used first
// Correct answer is followed with "right"
// all wrong ones with ""
questions[0] = ["Which are gaming companies?:", "Valve", "right", "Microsoft", "", "Apple", "", "FedEx", ""]
questions[1] = ["Which is a game?:", "Micrsoft Word", "", "Piskel", "", "Dota 2", "right", "csTimer.net", ""]
// To display question array list
for (i = 0; i < questions.length; i++) {
for (j = 0; j < questions[i].length; j++) {
if (questions[i][j] == "")
questions[i][j] = ("w" + i) + j
if (questions[i][j] == "right")
questions[i][j] = "right" + i
}
}
var ie = document.all
// diplays answer holder when button is pressed
function showAnswer(el, ans) {
ie ? ie[el].innerHTML = 'The answer is: ' + ans : document.getElementById(el).innerHTML = 'The answer is: ' + ans
}
function addup() {
var q, right, statement, total = 0
quizQuests = new Array();
for (i = 0; i < questions.length; i++)
quizQuests[i] = 0
if (document.forms.quiz.q0['right0']) {
for (i = 0; i < questions.length; i++) {
q = "q" + i
right = "right" + i
// takes away 1 if incorrect!
if (document.forms.quiz[q][right].checked)
quizQuests[i] += -1
}
} else if (document.getElementById) {
for (i = 0; i < questions.length; i++) {
right = "right" + i
// adds 2 if correct!
if (document.getElementById(right).checked)
quizQuests[i] = 2
}
} else
return;
for (i = 0; i < questions.length; i++)
total += quizQuests[i]
// Displays end score (Attempted to get percentage but remove as it wouldn't calculate correctly)
statement = 'You scored ' + total + ' points out of 20'
ie ? ie.results.innerHTML = statement : document.getElementById('results').innerHTML = statement
}
function clearR() {
ie ? ie.results.innerHTML = '' : document.getElementById('results').innerHTML = ''
for (i = 0; i < questions.length; i++)
if (allowPeeking)
ie ? ie["ans" + i].innerHTML = '' : document.getElementById("ans" + i).innerHTML = ''
window.scrollTo(0, 0);
}
document.write('<hr><form name="quiz">')
var correct, answersString
// displaying answers & checking correct / wrong choices
for (i = 0; i < questions.length; i++) {
answersString = ''
for (k = 1; k < questions[i].length; k += 2)
answersString += '<input id="' + questions[i][(k + 1)] + '" type="radio" unchecked name="q' + i + '"><label for="' + questions[i][(k + 1)] + '">' + questions[i][k] + '</label><br>'
for (j = 0; j < questions[i].length; j++) {
if (questions[i][j] == "right" + i)
correct = questions[i][j - 1]
}
with(document) {
write('Question ' + (i + 1) + ':<br><br>')
write(questions[i][0] + '<br>')
write(answersString)
// simply displays answer ("right" - 1)
if (allowPeeking)
write('<input class="chkans" type="button" value="Check Answer" onclick="showAnswer(\'ans' + i + '\',\'' + correct + '\')"> <span id="ans' + i + '" class="chkans"></span><br> ')
write('<br>')
}
}
with(document) {
// calls addup function
write('<hr><br>')
write('<input type="button" value="See Score" onclick="addup()"> <span id="results"></span><br> <br>')
// calls clearR function
if (allowDoOvers)
write('<input type="button" value="Start Again" onclick="reset();clearR()">')
write('</form>')
}
</script>
</body>
</html>
Appreciate any help given.
Check below answer. The timer will stop when you click the button See Score.
<html>
<head>
<title>Best Gaming Quiz Ever!</title>
</head>
<body>
<h1>Gaming Quiz</h1>
We have made 10 questions for you to answer about gaming and gaming companies. Do your best, and don't guess,
<br>it's really not that difficult. Also, try not to be a cheating noob and click "check answer" before you make your choice!
<br>Challenge yourself, and have fun!
<h2>Your mission:</h2>
Just pick the correct answer, duh, it's a quiz, what else?
<br>
<br>
<hr>
<br>
<b>Time taken:</b> <span id="timer">0</span> seconds
<br>
<br>
<script type="text/javascript">
var t = 0;
var runTimer = setInterval(function() {
t++;
document.getElementById("timer").innerHTML = t;
}, 1000);
var allowPeeking = 1
var allowDoOvers = 1
questions = new Array();
// Q & A questions set as Arrays below
// Questions are used first
// Correct answer is followed with "right"
// all wrong ones with ""
questions[0] = ["Which are gaming companies?:", "Valve", "right", "Microsoft", "", "Apple", "", "FedEx", ""]
questions[1] = ["Which is a game?:", "Micrsoft Word", "", "Piskel", "", "Dota 2", "right", "csTimer.net", ""]
// To display question array list
for (i = 0; i < questions.length; i++) {
for (j = 0; j < questions[i].length; j++) {
if (questions[i][j] == "")
questions[i][j] = ("w" + i) + j
if (questions[i][j] == "right")
questions[i][j] = "right" + i
}
}
var ie = document.all
// diplays answer holder when button is pressed
function showAnswer(el, ans) {
ie ? ie[el].innerHTML = 'The answer is: ' + ans : document.getElementById(el).innerHTML = 'The answer is: ' + ans
}
function addup() {
clearInterval(runTimer);
var q, right, statement, total = 0
quizQuests = new Array();
for (i = 0; i < questions.length; i++)
quizQuests[i] = 0
if (document.forms.quiz.q0['right0']) {
for (i = 0; i < questions.length; i++) {
q = "q" + i
right = "right" + i
// takes away 1 if incorrect!
if (document.forms.quiz[q][right].checked)
quizQuests[i] += -1
}
} else if (document.getElementById) {
for (i = 0; i < questions.length; i++) {
right = "right" + i
// adds 2 if correct!
if (document.getElementById(right).checked)
quizQuests[i] = 2
}
} else
return;
for (i = 0; i < questions.length; i++)
total += quizQuests[i]
// Displays end score (Attempted to get percentage but remove as it wouldn't calculate correctly)
statement = 'You scored ' + total + ' points out of 20'
ie ? ie.results.innerHTML = statement : document.getElementById('results').innerHTML = statement
}
function clearR() {
ie ? ie.results.innerHTML = '' : document.getElementById('results').innerHTML = ''
for (i = 0; i < questions.length; i++)
if (allowPeeking)
ie ? ie["ans" + i].innerHTML = '' : document.getElementById("ans" + i).innerHTML = ''
window.scrollTo(0, 0);
}
document.write('<hr><form name="quiz">')
var correct, answersString
// displaying answers & checking correct / wrong choices
for (i = 0; i < questions.length; i++) {
answersString = ''
for (k = 1; k < questions[i].length; k += 2)
answersString += '<input id="' + questions[i][(k + 1)] + '" type="radio" unchecked name="q' + i + '"><label for="' + questions[i][(k + 1)] + '">' + questions[i][k] + '</label><br>'
for (j = 0; j < questions[i].length; j++) {
if (questions[i][j] == "right" + i)
correct = questions[i][j - 1]
}
with(document) {
write('Question ' + (i + 1) + ':<br><br>')
write(questions[i][0] + '<br>')
write(answersString)
// simply displays answer ("right" - 1)
if (allowPeeking)
write('<input class="chkans" type="button" value="Check Answer" onclick="showAnswer(\'ans' + i + '\',\'' + correct + '\')"> <span id="ans' + i + '" class="chkans"></span><br> ')
write('<br>')
}
}
with(document) {
// calls addup function
write('<hr><br>')
write('<input type="button" value="See Score" onclick="addup()"> <span id="results"></span><br> <br>')
// calls clearR function
if (allowDoOvers)
write('<input type="button" value="Start Again" onclick="reset();clearR()">')
write('</form>')
}
</script>
</body>
</html>

Change obj.innerHTML in Javascript? Game of Life

I have implemented the Game of Life in Javascript. I am thinking about making a combobox which a listof colors to choose from. From there I want to render the obj.innerHTML img source of my grid cells in the game. What would be the best way to go about this?
Here is my code so far for the game:
<br>
<canvas id="canvas" width="100%" height="80%"></canvas>
<button onClick="generateLevel()">Create New Board</button>
<button onClick="step()">Step</button>
<button onClick="multiStep()">Multistep</button>
<script type="text/javascript">
var level;
var lastLevelDrawn;
var lvlWidth = 0;
var lvlHeight = 0;
function step()
{
var tempLevel = new Array(lvlHeight);
for (var y = 0; y < lvlHeight; y++)
{
tempLevel[y] = new Array(lvlWidth);
for (var x = 0; x < lvlWidth; x++)
{
var liveNeighborCount = 0;
var status = level[y][x];
for (var k = y-1; k < y+2; k++)
{
for (var j = x-1; j < x+2; j++)
{
if (k == y && j == x)
{
}
else if (k >= 0 && k < lvlHeight && j >= 0 && j < lvlWidth)
{
if (level[k][j] == "1")
{
liveNeighborCount++;
}
}
}
}
if (level[y][x] == "1")
{
if (liveNeighborCount != 2 && liveNeighborCount != 3)
{
status = "0";
}
}
if (level[y][x] == "0")
{
if (liveNeighborCount == 3)
{
status = "1";
}
}
tempLevel[y][x] = status;
}
}
level = tempLevel;
render();
}
function multiStep()
{
var steps = prompt("How many steps do you want to step?", "10");
for (var x = 0; x < steps; x++)
step();
}
function generateLevel()
{
var width = prompt("How many cells wide?", "10");
var height = prompt("How many cells high?", "10");
lvlWidth = width;
lvlHeight = height;
var output = "";
if (width != null && height != null)
{
level = new Array(lvlHeight);
lastLevelDrawn = new Array(lvlHeight);
for (var y = 0; y < height; y++)
{
level[y] = new Array(lvlWidth);
lastLevelDrawn[y] = new Array(lvlWidth);
for (var x = 0; x < width; x++)
{
level[y][x] = Math.floor((Math.random()*2));
lastLevelDrawn[y][x] = -1;
output += " " + level[y][x];
}
output += "<br>";
}
}
//document.getElementById("demo").innerHTML=output;
setupRender();
}
function changeTile(tile)
{
var x = tile % lvlWidth;
var y = parseInt(tile/lvlWidth);
//document.getElementById("demo").innerHTML=x + ":" + y;
if (level[y][x] == "1")
level[y][x] = "0";
else
level[y][x] = "1";
render();
}
function render()
{
var widPer = ((1/lvlWidth)*90);
var heiPer = ((1/lvlHeight)*70);
for (var y = 0; y < lvlHeight; y++)
{
for (var z = 0; z < lvlWidth; z++)
{
var send = y*lvlWidth + z;
if (lastLevelDrawn[y][z] != level[y][z])
{
lastLevelDrawn[y][z] = level[y][z];
var obj = document.getElementById(send);
if (level[y][z] == "1")
obj.innerHTML = "<img src='white.jpg' width='" + widPer + "%' height='" + heiPer + "%' onclick='changeTile(" + send + ")'/>";
else
obj.innerHTML = "<img src='black.jpg' width='" + widPer + "%' height='" + heiPer + "%' onclick='changeTile(" + send + ")'/>";
}
}
}
}
function setupRender()
{
var x = "";
var widPer = ((1/lvlWidth)*90);
var heiPer = ((1/lvlHeight)*70);
//x += "<table border='1' col width='((1/lvlWidth)*100)%' col height='((1/lvlHeight)*80)%'>";
for (var y = 0; y < lvlHeight; y++)
{
//x += "<tr>";
for (var z = 0; z < lvlWidth; z++)
{
lastLevelDrawn[y][z] = level[y][z];
//x += level[y][z];
var send = y*lvlWidth + z;
x += "<n id='" + send + "'>";
if (level[y][z] == "1")
x += "<img src='white.jpg' width='" + widPer + "%' height='" + heiPer + "%' onclick='changeTile(" + send + ")'/>";
else
x += "<img src='black.jpg' width='" + widPer + "%' height='" + heiPer + "%' onclick='changeTile(" + send + ")'/>";
x += "</n>";
}
x += "<br>";
//x += "</tr>";
}
//x += "</table>";
document.getElementById("demo").innerHTML=x;
}
</script>

Categories

Resources