Javascript Interval continues endless without conditions met - javascript

var counter;
var count = 0;
var equalsPressed = false;
var dritter = false;
var array = new Array();
window.onload = function() {
let x = document.getElementsByClassName('zahlen')
let i;
for (i = 0; i < x.length; i++) {
let y = x[i];
x[i].addEventListener('mousedown', function() {
add(this.className, this.value.replace(/\s/g, ''));
}, true);
//x[i].addEventListener(mousedown,function('Hi')
x[i].onmousedown = debounce(function() {
start(y.className, y.value.replace(/\s/g, ''));
}, 200);
}
}
function debounce(a, b) {
return function() {
let timer;
clearTimeout(timer);
booli = true;
timer = setTimeout(function() {
if (booli) {
a();
} else {
clearInterval(counter);
}
}, b);
};
}
function start(clicked_className, Zeichen) {
counter = setInterval(function() {
add(clicked_className, Zeichen);
count++;
}, 370);
}
function end() {
booli = false;
clearInterval(counter);
}
function Check(Eingabe) {
// indexof=suche in "0123456789[]()-+*%/" nach den chars der eingabe(0 bis 1 kleiner als länge (also alle)) und schaue an welcher position im string diese sind.wenn position kleiner0(also nicht vorhanden)
// dann return false, ansonsten alles gut
var inhalt = "0123456789[]().-+*%/=e";
for (var i = 0; i < Eingabe.length; i++)
if (inhalt.indexOf(Eingabe.charAt(i)) < 0) return false;
return true;
}
function Ergebnis() {
var z = document.getElementById("Historie");
z.style.display = "block";
var ausg = 0;
if (equalsPressed && Check(window.document.Rechner.Display.value)) {
var o = window.document.Rechner.Display2.value;
var p = window.document.Rechner.Display.value;
p = p.replace("=", '');
const chars = ["+", "-", "*", "/"];
var last;
for (const rechenarten of o) {
if (chars.includes(rechenarten)) {
last = rechenarten;
}
}
//lastIndexOf zählt von hinten und fängt bei o.length - 1 also der letzten Position an
//und sucht last, also die am weitesten hinten vorkommende der Rechenarten
o = o.slice(o.lastIndexOf(last, o.length - 1), o.lenght);
ausg = eval(p + o);
ausg = ausg.toFixed(getDecimalPlaces(p));
window.document.Rechner.Display.value = ausg;
window.document.Rechner.Display2.value = window.document.Rechner.Display2.value + o;
dritter = true;
} else {
var y = 0;
var x = 0;
if (Check(window.document.Rechner.Display.value))
y = window.document.Rechner.Display.value;
window.document.Rechner.Display2.value = y;
ausg = eval(window.document.Rechner.Display.value);
ausg = ausg.toFixed(getDecimalPlaces(y)); //
window.document.Rechner.Display.value = "=" + ausg;
}
}
function getDecimalPlaces(numb) {
var highest = 0;
var counter = 0;
for (a = 0; a < numb.length; a++) {
if (numb.charAt(a - 1) == ".") {
do {
counter++;
a++;
}
while (!isNaN(numb.charAt(a)) && a < numb.length);
}
if (counter > highest) {
highest = counter;
}
counter = 0;
}
return highest;
}
function add(clicked_className, Zeichen) {
if (equalsPressed == false && clicked_className == 'zahlen') {
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
} else if (dritter && equalsPressed && clicked_className == 'zahlen') {
var array = new Array();
array.push(window.document.Rechner.Display2.value + "=" +
window.document.Rechner.Display.value);
var myTableDiv = document.getElementById("Historie")
var table = document.createElement('TABLE')
var tableBody = document.createElement('TBODY')
table.border = '0';
table.appendChild(tableBody);
var tr = document.createElement('TR');
tableBody.appendChild(tr);
var td = document.createElement('TD')
td.width = '275';
td.style.textAlign = "right";
td.appendChild(document.createTextNode(array[0]));
tr.appendChild(td);
myTableDiv.appendChild(table)
window.document.Rechner.Display2.value = "";
window.document.Rechner.Display.value = "";
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
equalsPressed = false;
} else if (equalsPressed && clicked_className == 'zahlen') {
window.document.Rechner.Display2.value = "";
window.document.Rechner.Display.value = "";
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
equalsPressed = false;
} else if (clicked_className == 'ops') {
var x;
window.document.Rechner.Display.value = window.document.Rechner.Display.value.replace("=", '');
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
equalsPressed = false;
}
}
function gleichPressed() {
equalsPressed = true;
}
function backspace() {
var abschneiden = window.document.Rechner.Display.value;
for (var i = 0; i < abschneiden.length; i++) {
var output = abschneiden.slice(0, -1);
window.document.Rechner.Display.value = output;
}
}
function ausgabe() {
if (equalsPressed) {
} else {
array.push(window.document.Rechner.Display2.value +
window.document.Rechner.Display.value);
console.log(array);
var myTableDiv = document.getElementById("Historie")
var table = document.createElement('TABLE')
var tableBody = document.createElement('TBODY')
table.border = '0';
table.appendChild(tableBody);
var tr = document.createElement('TR');
tableBody.appendChild(tr);
var td = document.createElement('TD')
td.width = '275';
td.style.textAlign = "right";
td.appendChild(document.createTextNode(array[0]));
tr.appendChild(td);
myTableDiv.appendChild(table)
}
}
body {
font-family: "Century Gothic", CenturyGothic, Geneva, AppleGothic, sans-serif;
}
.button,
.ops,
.zahlen,
.sonst,
.istgleich {
background-color: #A4A4A4;
background: linear-gradient(240deg, grey, white);
color: black;
width: 60px;
text-align: center;
font-family: System, sans-serif;
font-size: 100%;
}
.button:hover,
.zahlen:hover,
.sonst:hover,
.ops:hover,
.istgleich:hover {
color: #2E2E2E;
background-color: #FAFAFA;
background: linear-gradient(30deg, darkgrey, lightgrey, grey);
;
}
.display {
width: 100%;
text-align: right;
font-family: System, sans-serif;
font-size: 100%;
}
#Historie {
background: linear-gradient(30deg, silver, white, grey);
;
border: 5px outset;
float: left;
text-align: right;
}
#eins {
background: linear-gradient(30deg, silver, grey, DimGray);
;
}
#zwei {
background: linear-gradient(90deg, silver, grey);
;
}
#tabelle {
width: 300px;
height: 235px;
float: left;
}
<html onmouseup="end()">
<head>
<meta charset="UTF-8">
<title>Taschenrechner</title>
</head>
<body bgcolor="#FFFFE0" text="#000000">
<form name="Rechner" action="" onSubmit="Ergebnis();return false;">
<table id="tabelle" style="float:left" border="7" cellpadding="12" cellspacing="0">
<tr>
<td id="eins">
<input type="text" name="Display2" class="display" readonly>
<input type="text" name="Display" class="display" readonly></td>
</tr>
<tr>
<td id="zwei">
<table border="1" cellpadding="0" cellspacing="0">
<tr>
<td><input type="button" class="zahlen" value=" 7 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 8 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 9 " onmouseleave="end()">
</td>
<td><input type="button" class="sonst" value=" &#171 " onClick="backspace()">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" 4 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 5 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 6 " onmouseleave="end()">
</td>
<td><input type="button" class="ops" value=" + " onClick="add(this.className,'+')">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" 1 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 2 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 3 " onmouseleave="end()">
</td>
<td><input type="button" class="ops" value=" - " onClick="add(this.className,'-')">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" . ">
</td>
<td><input type="button" class="zahlen" value=" 0 " onmouseleave="end()">
</td>
<td><input type="button" class="istgleich" value=" = " onClick="Ergebnis();ausgabe();gleichPressed()">
</td>
<td><input type="button" class="ops" value=" * " onClick="add(this.className,'*')">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" ( ">
</td>
<td><input type="button" class="zahlen" value=" ) ">
</td>
<td><input type="reset" class="button" value=" C ">
</td>
<td><input type="button" class="ops" value=" / " onClick="add(this.className,'/')">
</td>
</tr>
</table>
</td>
</tr>
</table>
</form>
<div class="Historie" id="Historie" hidden="true">
</div>
</body>
</html>
Instruction___: doubleclick and hold
Im really really helpless in finding that bug tried to find where it originates, and build in couple of booleans so the loop only runs if theyre true but they were all false and it still continued running.
Im looking for a solution or a good way to adress the problem:(
What i found very noteworthy is that it only occurs when doing the needed keypresses fast, if done slower it doesnt result in that bug, also when done multiple times, it loops multiple times.

Just like Bergi said, your debounce function is broken. You need to initialize the timer variable outside the returned function.
This is your implementation:
function debounce(a, b) {
return function() {
let timer;
clearTimeout(timer);
booli = true;
timer = setTimeout(function() {
if (booli) {
a();
} else {
clearInterval(counter);
}
}, b);
};
}
And this is how you fix your bug:
function debounce(a, b) {
let timer;
return function() {
clearTimeout(timer);
booli = true;
timer = setTimeout(function() {
if (booli) {
a();
} else {
clearInterval(counter);
}
}, b);
};
}
var counter;
var count = 0;
var equalsPressed = false;
var dritter = false;
var array = new Array();
window.onload = function() {
let x = document.getElementsByClassName('zahlen')
let i;
for (i = 0; i < x.length; i++) {
let y = x[i];
x[i].addEventListener('mousedown', function() {
add(this.className, this.value.replace(/\s/g, ''));
}, true);
//x[i].addEventListener(mousedown,function('Hi')
x[i].onmousedown = debounce(function() {
start(y.className, y.value.replace(/\s/g, ''));
}, 200);
}
}
function debounce(a, b) {
let timer;
return function() {
clearTimeout(timer);
booli = true;
timer = setTimeout(function() {
if (booli) {
a();
} else {
clearInterval(counter);
}
}, b);
};
}
function start(clicked_className, Zeichen) {
counter = setInterval(function() {
add(clicked_className, Zeichen);
count++;
}, 370);
}
function end() {
booli = false;
clearInterval(counter);
}
function Check(Eingabe) {
// indexof=suche in "0123456789[]()-+*%/" nach den chars der eingabe(0 bis 1 kleiner als länge (also alle)) und schaue an welcher position im string diese sind.wenn position kleiner0(also nicht vorhanden)
// dann return false, ansonsten alles gut
var inhalt = "0123456789[]().-+*%/=e";
for (var i = 0; i < Eingabe.length; i++)
if (inhalt.indexOf(Eingabe.charAt(i)) < 0) return false;
return true;
}
function Ergebnis() {
var z = document.getElementById("Historie");
z.style.display = "block";
var ausg = 0;
if (equalsPressed && Check(window.document.Rechner.Display.value)) {
var o = window.document.Rechner.Display2.value;
var p = window.document.Rechner.Display.value;
p = p.replace("=", '');
const chars = ["+", "-", "*", "/"];
var last;
for (const rechenarten of o) {
if (chars.includes(rechenarten)) {
last = rechenarten;
}
}
//lastIndexOf zählt von hinten und fängt bei o.length - 1 also der letzten Position an
//und sucht last, also die am weitesten hinten vorkommende der Rechenarten
o = o.slice(o.lastIndexOf(last, o.length - 1), o.lenght);
ausg = eval(p + o);
ausg = ausg.toFixed(getDecimalPlaces(p));
window.document.Rechner.Display.value = ausg;
window.document.Rechner.Display2.value = window.document.Rechner.Display2.value + o;
dritter = true;
} else {
var y = 0;
var x = 0;
if (Check(window.document.Rechner.Display.value))
y = window.document.Rechner.Display.value;
window.document.Rechner.Display2.value = y;
ausg = eval(window.document.Rechner.Display.value);
ausg = ausg.toFixed(getDecimalPlaces(y)); //
window.document.Rechner.Display.value = "=" + ausg;
}
}
function getDecimalPlaces(numb) {
var highest = 0;
var counter = 0;
for (a = 0; a < numb.length; a++) {
if (numb.charAt(a - 1) == ".") {
do {
counter++;
a++;
}
while (!isNaN(numb.charAt(a)) && a < numb.length);
}
if (counter > highest) {
highest = counter;
}
counter = 0;
}
return highest;
}
function add(clicked_className, Zeichen) {
if (equalsPressed == false && clicked_className == 'zahlen') {
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
} else if (dritter && equalsPressed && clicked_className == 'zahlen') {
var array = new Array();
array.push(window.document.Rechner.Display2.value + "=" +
window.document.Rechner.Display.value);
var myTableDiv = document.getElementById("Historie")
var table = document.createElement('TABLE')
var tableBody = document.createElement('TBODY')
table.border = '0';
table.appendChild(tableBody);
var tr = document.createElement('TR');
tableBody.appendChild(tr);
var td = document.createElement('TD')
td.width = '275';
td.style.textAlign = "right";
td.appendChild(document.createTextNode(array[0]));
tr.appendChild(td);
myTableDiv.appendChild(table)
window.document.Rechner.Display2.value = "";
window.document.Rechner.Display.value = "";
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
equalsPressed = false;
} else if (equalsPressed && clicked_className == 'zahlen') {
window.document.Rechner.Display2.value = "";
window.document.Rechner.Display.value = "";
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
equalsPressed = false;
} else if (clicked_className == 'ops') {
var x;
window.document.Rechner.Display.value = window.document.Rechner.Display.value.replace("=", '');
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
equalsPressed = false;
}
}
function gleichPressed() {
equalsPressed = true;
}
function backspace() {
var abschneiden = window.document.Rechner.Display.value;
for (var i = 0; i < abschneiden.length; i++) {
var output = abschneiden.slice(0, -1);
window.document.Rechner.Display.value = output;
}
}
function ausgabe() {
if (equalsPressed) {
} else {
array.push(window.document.Rechner.Display2.value +
window.document.Rechner.Display.value);
console.log(array);
var myTableDiv = document.getElementById("Historie")
var table = document.createElement('TABLE')
var tableBody = document.createElement('TBODY')
table.border = '0';
table.appendChild(tableBody);
var tr = document.createElement('TR');
tableBody.appendChild(tr);
var td = document.createElement('TD')
td.width = '275';
td.style.textAlign = "right";
td.appendChild(document.createTextNode(array[0]));
tr.appendChild(td);
myTableDiv.appendChild(table)
}
}
body {
font-family: "Century Gothic", CenturyGothic, Geneva, AppleGothic, sans-serif;
}
.button,
.ops,
.zahlen,
.sonst,
.istgleich {
background-color: #A4A4A4;
background: linear-gradient(240deg, grey, white);
color: black;
width: 60px;
text-align: center;
font-family: System, sans-serif;
font-size: 100%;
}
.button:hover,
.zahlen:hover,
.sonst:hover,
.ops:hover,
.istgleich:hover {
color: #2E2E2E;
background-color: #FAFAFA;
background: linear-gradient(30deg, darkgrey, lightgrey, grey);
;
}
.display {
width: 100%;
text-align: right;
font-family: System, sans-serif;
font-size: 100%;
}
#Historie {
background: linear-gradient(30deg, silver, white, grey);
;
border: 5px outset;
float: left;
text-align: right;
}
#eins {
background: linear-gradient(30deg, silver, grey, DimGray);
;
}
#zwei {
background: linear-gradient(90deg, silver, grey);
;
}
#tabelle {
width: 300px;
height: 235px;
float: left;
}
<html onmouseup="end()">
<head>
<meta charset="UTF-8">
<title>Taschenrechner</title>
</head>
<body bgcolor="#FFFFE0" text="#000000">
<form name="Rechner" action="" onSubmit="Ergebnis();return false;">
<table id="tabelle" style="float:left" border="7" cellpadding="12" cellspacing="0">
<tr>
<td id="eins">
<input type="text" name="Display2" class="display" readonly>
<input type="text" name="Display" class="display" readonly></td>
</tr>
<tr>
<td id="zwei">
<table border="1" cellpadding="0" cellspacing="0">
<tr>
<td><input type="button" class="zahlen" value=" 7 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 8 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 9 " onmouseleave="end()">
</td>
<td><input type="button" class="sonst" value=" &#171 " onClick="backspace()">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" 4 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 5 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 6 " onmouseleave="end()">
</td>
<td><input type="button" class="ops" value=" + " onClick="add(this.className,'+')">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" 1 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 2 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 3 " onmouseleave="end()">
</td>
<td><input type="button" class="ops" value=" - " onClick="add(this.className,'-')">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" . ">
</td>
<td><input type="button" class="zahlen" value=" 0 " onmouseleave="end()">
</td>
<td><input type="button" class="istgleich" value=" = " onClick="Ergebnis();ausgabe();gleichPressed()">
</td>
<td><input type="button" class="ops" value=" * " onClick="add(this.className,'*')">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" ( ">
</td>
<td><input type="button" class="zahlen" value=" ) ">
</td>
<td><input type="reset" class="button" value=" C ">
</td>
<td><input type="button" class="ops" value=" / " onClick="add(this.className,'/')">
</td>
</tr>
</table>
</td>
</tr>
</table>
</form>
<div class="Historie" id="Historie" hidden="true">
</div>
</body>
</html>

Related

table selection with CSS/html

i have a 5x5 grid and im using tables to do it and i am able to edit using css the first 5 the but cant do the rest.
Is there away i can change the colour of each individual cell. I need an empty square 11 black squares and 13 white squares.
I have been trying to use this but this only works up to to the td:nth-child(1)
.box tbody tr:first-child td:nth-child(1) {
width: 60px;
height: 60px;
margin: 1px;
text-align: center;
background-color: black;
font-weight: bold;
font-size: x-large;
var id_empty;
var num_moves;
var isCompleted = false;
var time=0;
var nums = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25];
window.addEventListener("load", startTimer, false);
function startTimer()
{
window.setInterval("updateTime()", 1000);
}
function updateTime()
{
++time;
document.getElementById("time").innerHTML ="Current Time: " +time +" (seconds)";
}
function startPuzzle() {
num_moves = 0;
isCompleted = false;
for(var i=0; i < 25; i++) {
var tmp = document.getElementById(i);
tmp.className = "cell ";
}
randomNumber = nums.sort(function () { return (Math.round(Math.random())-0.5);});
while(!Problem.prototype.is_solvable(randomNumber)) {
randomNumber = nums.sort(function () { return (Math.round(Math.random())-0.5);});
}
for(var i=0; i < 25; i++) {
var tmp = document.getElementById(i);
if(randomNumber[i] == 25) {
tmp.className = "cell empty";
tmp.innerHTML = "";
id_empty = i;
}
else
tmp.innerHTML = randomNumber[i];
}
}
function clickCell(x)
{
if(isCompleted)
return;
if(x.id != id_empty+'') {
var emptyI = Math.floor(id_empty/5);
var emptyJ = id_empty % 5;
var id_selected = Number(x.id);
var selectedI = Math.floor(id_selected/5);
var selectedJ = id_selected % 5;
if((Math.abs(emptyI - selectedI) == 1 && emptyJ == selectedJ) ||
(Math.abs(emptyJ - selectedJ) == 1 && emptyI == selectedI)) {
document.getElementById(id_empty).className = "cell";
document.getElementById(id_empty).innerHTML = x.innerHTML;
x.className = "cell empty";
x.innerHTML = '';
id_empty = id_selected;
num_moves++;
document.getElementById("moves").innerHTML = "Moves so far: " + num_moves;
if(isDone()){
isCompleted = true;
document.getElementById("moves").innerHTML = "Letter complete - Shuffle tiles" + num_moves;
}
}
}
}
<!-- is done fuction can be used for letter recognition and is for future work -->
function isDone() {
return document.getElementById('0').innerHTML == '1' &&
document.getElementById('1').innerHTML == '2' &&
document.getElementById('2').innerHTML == '3' &&
document.getElementById('3').innerHTML == '4' &&
document.getElementById('4').innerHTML == '5' &&
document.getElementById('5').innerHTML == '6' &&
document.getElementById('6').innerHTML == '7' &&
document.getElementById('7').innerHTML == '8' &&
document.getElementById('8').innerHTML == '9' &&
document.getElementById('9').innerHTML == '10' &&
document.getElementById('10').innerHTML == '11' &&
document.getElementById('11').innerHTML == '12' &&
document.getElementById('12').innerHTML == '13' &&
document.getElementById('13').innerHTML == '14' &&
document.getElementById('14').innerHTML == '15' &&
document.getElementById('15').innerHTML == '16' &&
document.getElementById('16').innerHTML == '17' &&
document.getElementById('17').innerHTML == '18' &&
document.getElementById('18').innerHTML == '19' &&
document.getElementById('19').innerHTML == '20' &&
document.getElementById('20').innerHTML == '21' &&
document.getElementById('21').innerHTML == '22' &&
document.getElementById('22').innerHTML == '23' &&
document.getElementById('23').innerHTML == '24' &&
document.getElementById('24').innerHTML == '25' ;
}
function lastClick() {
var curr_state = currentState();
var problem = new Problem(curr_state);
var sol = Solver.a_star_search(problem);
var result = "<ol>";
for(var i = 0; i < sol.length; i++) {
var n = moveNumb(sol[i],curr_state);
curr_state = problem.result(sol[i],curr_state);
result += "<li>move " + n + "</li>";
}
result += "</ol>";
document.getElementById("steps").innerHTML = result;
}
function currentState() {
var result = [];
for(var i = 0; i < 25; i++) {
var tmp = document.getElementById(String(i)).innerHTML;
if(tmp == '') {
result[i] = 25;
}
else {
result[i] = Number(tmp);
}
}
return result;
}
function moveNumb(action,state) {
var i = state.indexOf(25);
switch(action) {
case Action.up:
return state[Util.index(Util.x(i),Util.y(i) - 1)];
case Action.down:
return state[Util.index(Util.x(i),Util.y(i) + 1)];
case Action.right:
return state[Util.index(Util.x(i) + 1,Util.y(i))];
case Action.left:
return state[Util.index(Util.x(i) - 1,Util.y(i))];
}
}
Array.prototype.clone = function() { return this.slice(0); };
Array.prototype.swap = function(i1,i2) {
var copy = this.clone();
var tmp = copy[i1];
copy[i1] = copy[i2];
copy[i2] = tmp;
return copy;
};
var Problem = function(start_state) {
this.init_state = start_state;
return this;
}
Problem.prototype.is_solvable = function(start) {
start = start.clone(); start.splice(start.indexOf(25), 1);
start[24] = 25;
var count = 0;
for(var i = 0; i < 24; i++) {
if(start[i] != i+1) {
count++;
var j = start.indexOf(i+1);
start[j] = start[i];
start[i] = i+1;
}
}
return count % 2 == 0;
}
.box {
border-style: solid;
border-color: black;
border-width: 5px;
margin: 5px;
}
.cell {
width: 60px;
height: 60px;
margin: 1px;
text-align: center;
background-color: black;
font-weight: bold;
font-size: x-large;
padding: 0px;
}
.wCell {
width: 60px;
height: 60px;
margin: 1px;
text-align: center;
background-color: white;
text:white;
font: black;
font-weight: bold;
font-size: x-large;
padding: 0px;
}
.empty {
background-color: white;
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<link href="style.css" rel="stylesheet" />
<script src="puzzle.js" type="text/javascript"></script>
</head>
<body onload="startPuzzle()">
<h2></h2>
<p id="moves"></p>
<p id="time"></p>
<p>
<button onclick="window.location.reload()">Shuffle Tiles</button>
</p>
<p>
</p>
<table class="box">
<tr>
<td id="0" class="wCell" onclick="clickCell(this)">1</td>
<td id="1" class="wCell" onclick="clickCell(this)">2</td>
<td id="2" class="wCell" onclick="clickCell(this)">3</td>
<td id="3" class="wCell" onclick="clickCell(this)">4</td>
<td id="4" class="wCell" onclick="clickCell(this)">5</td>
</tr>
<tr>
<td id="5" class="wCell" onclick="clickCell(this)">6</td>
<td id="6" class="wCell" onclick="clickCell(this)">7</td>
<td id="7" class="wCell" onclick="clickCell(this)">8</td>
<td id="8" class="wCell" onclick="clickCell(this)">9</td>
<td id="9" class="wCell" onclick="clickCell(this)">10</td>
</tr>
<tr>
<td id="10" class="wCell" onclick="clickCell(this)">11</td>
<td id="11" class="cell" onclick="clickCell(this)">12</td>
<td id="12" class="wcell" onclick="clickCell(this)">13</td>
<td id="13" class="wcell" onclick="clickCell(this)">14</td>
<td id="14" class="cell" onclick="clickCell(this)">15</td>
</tr>
<tr>
<td id="15" class="cell" onclick="clickCell(this)">16</td>
<td id="16" class="cell" onclick="clickCell(this)">17</td>
<td id="17" class="cell" onclick="clickCell(this)">18</td>
<td id="18" class="cell" onclick="clickCell(this)">19</td>
<td id="19" class="cell" onclick="clickCell(this)">20</td>
</tr>
<tr>
<td id="20" class="cell" onclick="clickCell(this)">21</td>
<td id="21" class="cell" onclick="clickCell(this)">22</td>
<td id="22" class="cell" onclick="clickCell(this)">23</td>
<td id="23" class="cell" onclick="clickCell(this)">24</td>
<td id="24" class="cell" onclick="clickCell(this)">25</td>
</tr>
</table>
</body>
</html>
Hi your every cell has different id you can use the id to colour each cell differently.
#12{ background: green;}
In this Snippet:
Every <td> is collected into an array
Next an array of 25 strings representing 11 black, 13 white, and 1 transparent is shuffled.
Then the newly shuffled array of colors and the array of <td>s are merged by .map() method.
As the 2 arrays are being merged, each pair is ran through a switch. This switch will color each <td> background.
A new array is returned comprising of the colored pattern the table is displaying.
SNIPPET
var x = 0,
y = 0,
temp = null;
// Collect every <td> into an array
const tiles = Array.from(document.querySelectorAll('td'));
const colors = ['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'w', 'w', 'w', 'w', 'w', 'w', 'w', 'w', 'w', 'w', 'w', 'w', 'w', 't'];
// Fisher-Yates Shuffle
for (x = colors.length - 1; x > 0; x -= 1) {
y = Math.floor(Math.random() * (x + 1));
temp = colors[x];
colors[x] = colors[y];
colors[y] = temp;
}
console.log(colors);
// Map() both arrays into one
const mixArray = tiles.map(function(cell, idx) {
[cell, colors[idx]];
var cc = colors[idx];
// Determine tile color
switch (cc) {
case 'b':
cell.style.backgroundColor = 'black';
break;
case 'w':
cell.style.backgroundColor = 'white';
break;
case 't':
cell.style.backgroundColor = 'transparent';
break;
}
return cell;
});
console.log(mixArray);
table { border:1px solid grey; table-layout:fixed;}
tbody {background:#555;}
td {border:1px solid red; width:50px;height:50px;}
<table>
<tbody>
<tr class='A'>
<td class='A1'> </td>
<td class='A2'> </td>
<td class='A3'> </td>
<td class='A4'> </td>
<td class='A5'> </td>
</tr>
<tr class='B'>
<td class='B1'> </td>
<td class='B2'> </td>
<td class='B3'> </td>
<td class='B4'> </td>
<td class='B5'> </td>
</tr>
<tr class='C'>
<td class='C1'> </td>
<td class='C2'> </td>
<td class='C3'> </td>
<td class='C4'> </td>
<td class='C5'> </td>
</tr>
<tr class='D'>
<td class='D1'> </td>
<td class='D2'> </td>
<td class='D3'> </td>
<td class='D4'> </td>
<td class='D5'> </td>
</tr>
<tr class='E'>
<td class='E1'> </td>
<td class='E2'> </td>
<td class='E3'> </td>
<td class='E4'> </td>
<td class='E5'> </td>
</tr>
</tbody>
</table>

Automatic start time when a link is clicked [duplicate]

This question already has answers here:
Stop setInterval call in JavaScript
(7 answers)
Closed 5 years ago.
I would like to seek your expertise with regards to the coding below:
this is the layout of my browser, so i divided my page into 2
<FRAMESET rows="5%,*" border=0>
<FRAME SRC="MENU.HTML">
<FRAMESET rows="50%,*">
<FRAME SRC="" NAME=1>
<FRAME SRC="" NAME=2>
</FRAMESET>
</FRAMSET>
below is the code in which i would like to setup the start time automatic where in it will be the same start time in the label.
<html>
<head >
<title>Start and stop</TITLE>
<script type="text/javascript">
document.getElementById('date').value = Date();
</script>
<script>function getDateString(){
var myDate = new Date();
return padDatePart(myDate.getMonth() + 1) +
"/" + padDatePart(myDate.getDate()) +
"/" + myDate.getFullYear()+
' ' + padDatePart(myDate.getHours()) +
":" + padDatePart(myDate.getMinutes()) +
":" + padDatePart(myDate.getSeconds());
}
function padDatePart(part){
return ('0'+part).slice(-2);
}
</script>
<script>
function clearFields(formName)
{
var formElements = formName.elements;
for(var i=0;i<formElements.length;i++)
{
var elementType = formElements[i].type;
if('text' == elementType){
formElements[i].value="";
formElements[i].disabled = false;
}
else if('select-one' == elementType){
formElements[i].selectedIndex = 0;
formElements[i].disabled = false;
}
else if('select-multiple' == elementType)
{
var multiOptions = formElements[i].options;
for(var j=0;j<multiOptions.length;j++)
{
multiOptions[j].selected = false;
}
}
}
}
</script>
</head>
<form>
<body BGCOLOR=#FFFF99 SCROLL=NO>
<CENTER>
<table border=0>
<tr>
<td align=center>
<input onclick="this.form.StartTime.value = getDateString();" type="button" class=button value=" START " >
</td>
<td align=center>
<input onclick="this.form.StopTime.value =getDateString();" type="button" class=button value=" STOP ">
</td>
<TD COLSPAN=2 ALIGN=CENTER>
<input type="reset" class=button value=" CLEAR ">
</TD>
</tr>
</table>
<table>
<TR>
<TD colspan=2 align=center>
<input type="text" name="StartTime" size="17" id="date" class=select disabled="disabled">
| <label id="minutes">00</label>:<label id="seconds">00</label> |
<script type="text/javascript">
var minutesLabel = document.getElementById("minutes");
var secondsLabel = document.getElementById("seconds");
var totalSeconds = 0;
setInterval(setTime, 1000);
function setTime()
{
++totalSeconds;
secondsLabel.innerHTML = pad(totalSeconds%60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds/60));
}
function pad(val)
{
var valString = val + "";
if(valString.length < 2)
{
return "0" + valString;
}
else
{
return valString;
}
}
</script>
<input type="text" name="StopTime" size="17" class=select disabled="disabled">
</TD>
</TR>
</table>
</form>
</body>
</html>
</br></br></html>
is it possible to have automatic stop as well when i clicked the stop button?
Move the stuff that needs to be set after the page has rendered to an onload
make sure the table is wrapped in correct form tags
function pad(part) {
return ('0' + part).slice(-2);
}
function getDateString() {
var myDate = new Date();
return pad(myDate.getMonth() + 1) +
"/" + pad(myDate.getDate()) +
"/" + myDate.getFullYear() +
' ' + pad(myDate.getHours()) +
":" + pad(myDate.getMinutes()) +
":" + pad(myDate.getSeconds());
}
function clearFields(formName) {
var formElements = formName.elements;
for (var i = 0; i < formElements.length; i++) {
var elementType = formElements[i].type;
if ('text' == elementType) {
formElements[i].value = "";
formElements[i].disabled = false;
} else if ('select-one' == elementType) {
formElements[i].selectedIndex = 0;
formElements[i].disabled = false;
} else if ('select-multiple' == elementType) {
var multiOptions = formElements[i].options;
for (var j = 0; j < multiOptions.length; j++) {
multiOptions[j].selected = false;
}
}
}
}
function setTime() {
++totalSeconds;
secondsLabel.innerHTML = pad(totalSeconds % 60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));
}
var minutesLabel, secondsLabel, totalSeconds = 0;
window.onload = function() {
document.getElementById('date').value = Date();
minutesLabel = document.getElementById("minutes");
secondsLabel = document.getElementById("seconds");
setInterval(setTime, 1000);
}
<form>
<table border=0>
<tr>
<td align=center>
<input onclick="this.form.StartTime.value = getDateString();" type="button" class=button value=" START ">
</td>
<td align=center>
<input onclick="this.form.StopTime.value =getDateString();" type="button" class=button value=" STOP ">
</td>
<TD COLSPAN=2 ALIGN=CENTER>
<input type="reset" class=button value=" CLEAR ">
</TD>
</tr>
</table>
<table>
<TR>
<TD colspan=2 align=center>
<input type="text" name="StartTime" size="17" id="date" class=select disabled="disabled"> | <label id="minutes">00</label>:<label id="seconds">00</label> |
<input type="text" name="StopTime" size="17" class=select disabled="disabled">
</TD>
</TR>
</table>
</form>

Sample Calculator Application

I just made a simple calculator application with AngularJS.
What does this program can do:
Catch error input when I press . 2 times per series of numbers.
Only accept 10 numbers per series of numbers.
Check if not complete operate.
User only can do 1 formula per 1 series of numbers.
But there are still some bugs:
When max 10 numbers, if you press delete, the program still accepts more than 10 numbers?
Some time after calculation, the program allows to input max 12 numbers?
var mainApp = angular.module("mainApp", []);
mainApp.controller('CalCtrl', function($scope) {
$scope.output = "0";
$scope.curIndex = 0;
$scope.result = 0;
$scope.checkInput = function(num) {
var tmp = true;
if($scope.result != 0) {
$scope.result = 0;
$scope.output = "0";
tmp = true;
}
if(angular.equals('+', num) ||
angular.equals('-', num) ||
angular.equals('*', num) ||
angular.equals('/', num)) {
var index = "+|-|*|/".indexOf($scope.output.charAt($scope.output.length - 1));
if(index >= 0) {
tmp = false;
$scope.msg = "You only can do 1 formula per 1 time.";
}
$scope.curIndex = $scope.output.length + 1;
} else {
tmp = true;
if($scope.output.substring($scope.curIndex).length < 10) {
if(angular.equals(num, ".")) {
var k = 0;
for(var j = 0; j < $scope.output.substring($scope.curIndex).length; j++){
if(angular.equals(".", $scope.output.substring($scope.curIndex).charAt(j))) {
k = k + 1;
}
}
if(k >= 1){
$scope.msg = "You can't add '.' 2 times per series of numbers!";
tmp = false;
}
} else {
tmp = true;
}
} else {
$scope.msg = "You can't input more than 10 number per series of numbers!";
tmp = false;
}
}
return tmp;
}
$scope.operate = function(op) {
if($scope.checkInput(op)) {
$scope.output = $scope.output + op;
}
}
$scope.press = function(num) {
if($scope.checkInput(num)) {
if(angular.equals(num, 'x')){
$scope.output = $scope.output.slice(0 , $scope.output.length - 1);
} else {
if (angular.equals($scope.output, "0")) {
$scope.output = "";
$scope.msg = "";
$scope.output += num;
} else if (angular.equals(".", $scope.output)){
$scope.msg = "";
$scope.output = "0.";
$scope.output += num;
} else {
$scope.msg = "";
$scope.output += num;
}
}
} else {
if(angular.equals(num, 'x')){
$scope.msg = "";
$scope.output = $scope.output.slice(0 , $scope.output.length - 1);
}
}
}
$scope.equal = function() {
var isOpEnd = "+|-|*|/".indexOf($scope.output.charAt($scope.output.length - 1));
if(isOpEnd >= 0) {
$scope.msg = "You must complete the formula first!";
} else if(eval($scope.output) == 0){
$scope.output = "0";
} else {
$scope.msg = "";
$scope.result = eval($scope.output);
$scope.output = $scope.result;
}
}
});
table, th, td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f2f2f2;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<div ng-app="mainApp" align="center">
<h2>AngularJS Calculator Application by Rain</h2>
<div ng-controller="CalCtrl">
<table width="250px" height="300px" align="center">
<tr>
<td colspan="4">
<input type="text" style="text-align:center; width: 236px; height:30px" name="output" id="res" value="{{output}}" disabled = "disabled">
</td>
</tr>
<tr>
<td colspan="4">
<button title="Number 1" style="width:56px" ng-click="press('1')">1</button>
<button title="Number 2" style="width:56px" ng-click="press('2')">2</button>
<button title="Number 3" style="width:56px" ng-click="press('3')">3</button>
<button title="Operate +" style="width:56px" ng-click='operate("+")' >+</button>
</td>
</tr>
<tr>
<td colspan="4">
<button style="width:56px" ng-click="press('4')">4</button>
<button style="width:56px" ng-click="press('5')">5</button>
<button style="width:56px" ng-click="press('6')">6</button>
<button title="Operate -" style="width:56px" ng-click='operate("-")' >-</button>
</td>
</tr>
<tr>
<td colspan="4">
<button title="Number 7" style="width:56px" ng-click="press('7')">7</button>
<button title="Number 8" style="width:56px" ng-click="press('8')">8</button>
<button title="Number 9" style="width:56px" ng-click="press('9')">9</button>
<button title="Operate *" style="width:56px" ng-click='operate("*")' >x</button>
</td>
</tr>
<tr>
<td>
<button title="Number 0" style="width:56px" ng-click="press('0')">0</button>
<button title="." style="width:56px" ng-click="press('.')">.</button>
<button title="Clear all" style="width:56px" ng-click="output = '0'">C</button>
<button title="Operate ÷" style="width:56px" ng-click='operate("/")' >÷</button>
</td>
</tr>
<tr>
<td>
<button style="width:175px" ng-click="equal()">=</button>
<button title="Delete" style="width:56px" ng-click="press('x')">⌫</button>
</td>
</tr>
</table>
<span align="center" style="color:red">{{msg}}</span>
</div>
</div>

Vanilla JavaScript calculator

So I've been working on a "very simple" calculator only using vanilla JavaScript. However I don't know why is it now working.
This is my JavaScript and HTML code:
(function() {
"use strict";
var elem = function(element) {
if (element.charAt(0) === "#") {
return document.querySelector(element);
}
return document.querySelectorAll(element);
};
// Variables
var screen = elem('.screen');
equal = elem('.equal');
nums = elem('.num');
ops = elem('.operator');
theNum = "";
oldNum = "";
resultNum;
operator;
// When: Number is clicked. Get the current number selected
var setNum = function() {
if (resultNum) {
theNum = this.getAttribute('data-num');
resultNum = "";
} else {
theNum += this.getAttribute('data-num');
}
viewer.innerHTML = theNum;
};
var moveNum = function() {
oldNum = theNum;
theNum = "";
operator = this.getAttribute('data-ops');
equal.setAttribute('data-result', '');
};
var displayNum = function() {
oldNum = parseFloat(oldNum);
theNum = parseFloat(theNum);
switch (operator) {
case "plus":
resultNum = oldNum + theNum;
break;
case "minus":
resultNum = oldNum - theNum;
break;
case "times":
resultNum = oldNum * theNum;
break;
case "divided by":
resultNum = oldNum / theNum;
break;
default:
resultNum = theNum;
}
viewer.innerHTML = resultNum;
equal.setAttribute("data-result", resultNum);
oldNum = 0;
theNum = resultNum;
};
var clearAll = function() {
oldNum = "";
theNum = "";
viewer.innerHTML = "0";
equals.setAttribute("data-result", resultNum);
};
for (var i = 0, l = nums.length; i < l; i++) {
nums[i].onclick = setNum;
}
for (var i = 0, l = ops.length; i < l; i++) {
ops[i].onclick = moveNum;
}
equals.onclick = displayNum;
elem("#clear").onclick = clearAll;
<div id="calculator">
<div class="top">
<button id="clear">C</button>
<div class="screen"></div>
</div>
<div class="btns">
<button class="num" data-num="7">7</button>
<button class="num" data-num="8">8</button>
<button class="num" data-num="9">9</button>
<button class="operator" data-ops="plus">+</button>
<button class="num" data-num="4">4</button>
<button class="num" data-num="5">5</button>
<button class="num" data-num="6">6</button>
<button class="operator" data-ops="minus">-</button>
<button class="num" data-num="1">1</button>
<button class="num" data-num="2">2</button>
<button class="num" data-num="3">3</button>
<button class="operator" data-ops="divided by">÷</button>
<button class="num" data-num="0">0</button>
<button class="num" data-num=".">.</button>
<button class="equal" data-result="">=</button>
<button class="operator" data-ops="times">x</button>
</div>
</div>
I'm not sure if what I'm doing is correct. I've been pretty much improvising but if anyone knows an easier way or correct way of making the calculator work I'd really appreciate the help.
I wrote a basic calculator for a school assignment back in 2003. Even though the code is 12+ years old, it still works in modern browsers today. Feel free to check it out any borrow any code you might find useful.
You can find the complete code below as well as in this github repository.
By the way, the behavior of my calculator is intended to work exactly like that of a real, physical, old school calculator... which means that you need to push the on/c button before you can do anything else ;-)
A screenshot :
The code :
var on = false, lastprinted = "", currentfunc ="", memory;
function testoverflow() {
var overflowflag;
if (memory >= 1000000000000) {
turn("error");
overflowflag = true;
} else
overflowflag = false;
return overflowflag;
}
function findmaxlength(location) {
var maxlength = 12;
if (location.indexOf("-", 0) != -1) maxlength++;
if (location.indexOf(".", 0) != -1) maxlength++;
return maxlength;
}
function showresult(lg, hf) {
memory = memory.toString();
memory = parseFloat(memory.substring(0,findmaxlength(memory)));
document.calculator.display.value = memory;
lastprinted = lg;
currentfunc = hf;
}
function turn(onoff) {
if (onoff == "ce") {
if (on) {
document.calculator.display.value="0";
}
} else {
switch (onoff) {
case "onc":
document.calculator.display.value="0";
on = true;
break;
case "error":
document.calculator.display.value = "ERROR";
break;
case "off":
document.calculator.display.value="";
on = false;
break;
}
currentfunc = "";
memory = null;
}
lastprinted = "";
}
function number(input) {
if (on) {
if ((document.calculator.display.value.length < findmaxlength(document.calculator.display.value)) || (lastprinted != "number")) {
if (!((document.calculator.display.value == "0") && ((input == "00") || (input == "0")))) {
if ((lastprinted == "number")&&(document.calculator.display.value != "0")) {
document.calculator.display.value += input;
lastprinted = "number";
} else if (input != "00") {
document.calculator.display.value = input;
lastprinted = "number";
}
}
}
}
}
function func(symbool) {
if ((on) && (document.calculator.display.value != "ERROR")) {
if (memory == null) {
memory = parseFloat(document.calculator.display.value);
lastprinted = "func";
currentfunc = symbool;
} else if ((document.calculator.display.value == "0") && (currentfunc == "/")) {
turn("error");
} else {
eval("memory = " + memory + currentfunc + "(" + document.calculator.display.value +");");
if (! testoverflow()) showresult("func", symbool);
}
}
}
function result(name) {
var value;
if ((on) && (document.calculator.display.value != "ERROR")) {
if (memory != null) {
value = document.calculator.display.value;
if (name == "procent") value = memory * parseFloat(document.calculator.display.value)/ 100;
eval("memory = " + memory + currentfunc + "(" + value +");");
if (! testoverflow()) {
showresult("name", "");
memory = null;
}
}
}
}
function dot() {
var maxlength = 12;
if ((on) && (document.calculator.display.value != "ERROR")) {
if (document.calculator.display.value.indexOf("-", 0) != -1) maxlength++;
if (((lastprinted == "number") || (document.calculator.display.value="0")) && !(document.calculator.display.value.length >= maxlength) && (document.calculator.display.value.indexOf(".", 0) == -1)) {
document.calculator.display.value += ".";
lastprinted = "number";
}
}
}
function negative() {
if ((on) && (lastprinted == "number") && (document.calculator.display.value != "ERROR")) {
if (document.calculator.display.value.indexOf("-", 0) == -1) document.calculator.display.value = "-" + document.calculator.display.value;
else document.calculator.display.value = document.calculator.display.value.substring(1,14);
}
}
body {background-color: #CCCCCC; color: #555555; font-family: Arial; font-weight: bold; font-size: 8pt;}
a {color: #CC5555; text-decoration: none}
a:visited {color: #CC5555; text-decoration: none}
a:active {color: #FF0000; text-decoration: none}
a:hover {color: #FF0000; text-decoration: none}
.button {height: 30px; width: 40px; background-color: #555555; border-color: #555555; color:#FFFFFF;}
.invisbutton {height: 28px; width: 40px; background-color: #7555C6; border-color: #7555C6; border-style:solid;}
.display {height: 50px; width: 217px; background-color: #D6D39F; border-color: #000000; color:#222222; border-style: solid; text-align: right; font-size: 22pt;}
.redbutton {height: 30px; width: 40px; background-color: #EE0000; border-color: #EE0000; color:#FFFFFF;}
.yellowbutton {height: 30px; width: 40px; background-color: #EEEE00; border-color: #EEEE00; color:#000000;}
.device {height: 30px; width: 40px; background-color: #7555C6; border-color: #7555C6; border-style:ridge;}
<table class="device" cellspacing="20" cellpadding="0">
<tr>
<td align="center">
<form name="calculator">
<table>
<tr>
<td colspan="5"><input type="text" name="display" class="display" readonly='readonly'></td>
</tr>
<tr>
<td colspan="5"><input type="text" class="invisbutton" style="height:15px;" readonly='readonly'></td>
</tr>
<tr>
<td><input type="text" name="hidden" class="invisbutton" readonly='readonly'></td>
<td><input type="text" name="hidden2" class="invisbutton" readonly='readonly'></td>
<td><input type="button" name="off" class="redbutton" value="off" onclick="turn(this.name);"></td>
<td><input type="button" name="ce" class="yellowbutton" value="ce" onclick="turn(this.name);"></td>
<td><input type="button" name="onc" class="yellowbutton" value="on/c" onclick="turn(this.name);"></td>
</tr>
<tr>
<td><input type="button" name="number7" class="button" value="7" onclick="number(this.value);"></td>
<td><input type="button" name="number8" class="button" value="8" onclick="number(this.value);"></td>
<td><input type="button" name="number9" class="button" value="9" onclick="number(this.value);"></td>
<td><input type="button" name="procent" class="button" value="%" onclick="result(this.name);"></td>
<td><input type="button" name="plusmin" class="button" value="+/-" onclick="negative();"></td>
</tr>
<tr>
<td><input type="button" name="number4" class="button" value="4" onclick="number(this.value);"></td>
<td><input type="button" name="number5" class="button" value="5" onclick="number(this.value);"></td>
<td><input type="button" name="number6" class="button" value="6" onclick="number(this.value);"></td>
<td><input type="button" name="func-" class="button" value="-" onclick="func(this.name.substring(4, 5));"></td>
<td><input type="button" name="func/" class="button" value="/" onclick="func(this.name.substring(4, 5));"></td>
</tr>
<tr>
<td><input type="button" name="number1" class="button" value="1" onclick="number(this.value);"></td>
<td><input type="button" name="number2" class="button" value="2" onclick="number(this.value);"></td>
<td><input type="button" name="number3" class="button" value="3" onclick="number(this.value);"></td>
<td rowspan="2"><input type="button" name="func+" class="button" value="+" style="height: 64px" onclick="func(this.name.substring(4, 5));"></td>
<td><input type="button" name="func*" class="button" value="x" onclick="func(this.name.substring(4, 5));"></td>
</tr>
<tr>
<td><input type="button" name="number0" class="button" value="0" onclick="number(this.value);"></td>
<td><input type="button" name="number00" class="button" value="00" onclick="number(this.value);"></td>
<td><input type="button" name="dot" class="button" value="." onclick="dot();"></td>
<td><input type="button" name="equals" class="button" value="=" onclick="result(this.name);"></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
Are you closing your IIFE at the end of your code? If not, add
})();
to the end of your file.
separate
// Variables
var screen = elem('.screen');
equal = elem('.equal');
nums = elem('.num');
ops = elem('.operator');
theNum = "";
oldNum = "";
resultNum;
operator;
by commas, not semicolons.
Also, viewer is not defined.
There might be other things, but that should be a start
remove the function itself
add var before declaring variables: equal to viewer
use: var equal = elem('.equal')[0]; because you will get an array of DOM objects by className, you need the first one
use: var viewer = elem('.screen')[0]; because you will get an array of DOM objects by className, you need the first one
declare var viewer = elem('.screen');
Two words in the code 'equals' should be 'equal', remove the 's' in the end of the word
And the working code is:
"use strict";
var elem = function(element) {
if (element.charAt(0) === "#") {
return document.querySelector(element);
}
return document.querySelectorAll(element);
};
// Variables
var screen = elem('.screen');
var equal = elem('.equal')[0];
var nums = elem('.num');
var ops = elem('.operator');
var theNum = "";
var oldNum = "";
var resultNum;
var operator;
var viewer = elem('.screen')[0];
// When: Number is clicked. Get the current number selected
var setNum = function() {
if (resultNum) {
theNum = this.getAttribute('data-num');
resultNum = "";
} else {
theNum += this.getAttribute('data-num');
}
viewer.innerHTML = theNum;
};
var moveNum = function() {
oldNum = theNum;
theNum = "";
operator = this.getAttribute('data-ops');
equal.setAttribute('data-result', '');
};
var displayNum = function() {
oldNum = parseFloat(oldNum);
theNum = parseFloat(theNum);
switch (operator) {
case "plus":{
resultNum = oldNum + theNum;
break;
}
case "minus":
resultNum = oldNum - theNum;
break;
case "times":
resultNum = oldNum * theNum;
break;
case "divided by":
resultNum = oldNum / theNum;
break;
default:
resultNum = theNum;
}
viewer.innerHTML = resultNum;
equal.setAttribute("data-result", resultNum);
oldNum = 0;
theNum = resultNum;
};
var clearAll = function() {
oldNum = "";
theNum = "";
viewer.innerHTML = "0";
equal.setAttribute("data-result", resultNum);
};
for (var i = 0, l = nums.length; i < l; i++) {
nums[i].onclick = setNum;
}
for (var i = 0, l = ops.length; i < l; i++) {
ops[i].onclick = moveNum;
}
equal.onclick = displayNum;
elem("#clear").onclick = clearAll;

Autocomplete the numbers

I need to expand this code to make it so I have 9 x 9 board and when I put some nunbers in it then press the button it completes the 9x9 with numbers unique in line and column
<meta charset="utf-8">
<style>
input { font-size: 20px; width: 30px; text-align: center; }
</style>
<h1 id="a"></h1>
<button type="button" id="b" onClick="uzup()">uzupe�nij</button>
for( i=1; i<6; i++ ) {
document.getElementById('a').innerHTML += '<input id="a' + i + '" maxlength="1" pattern="^[1-5]$">';
}
function uzup() {
for(i=1;i<6;i++){
w = document.getElementById('a'+i).value;
if( w == '' ) {
w = Number(w);
for(j=1;j<6;j++){
jest = false;
for(k=1;k<6;k++){
w = document.getElementById('a'+k).value;
if( w != '' ){
if( Number(w) == j ) jest = true;
}
}
if( !jest ) {
document.getElementById('a'+i).value = j; break;
}
}
}
}
}
I don't know if I got it right. With an input like this
1 3 _
4 _ 5
5 _ 2
you want a result like this?
1 3 4
4 1 5
5 4 2
is that correct?
I tried to do it in the most obvious and legible way (real code would do it in about 10% of that amount of lines but would have the legibility of a well designed Perl script ;-) and I hope you understand the flow without extensive comments.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Nine By Nine</title>
<script type="text/javascript">
function clearTable(){
for(var i = 0; i<9; i++){
document.getElementById("c"+i).style.border = "1px solid grey";
document.getElementById("i"+i).value = "";
}
}
// Some checks & balances omitted!
function fillUp(){
var m = [],d,c,r;
var gotoError = function(idx){
document.getElementById("c"+idx).style.border = "1px solid red";
};
var checkField = function(n, row, col){
for(var i=0;i<3;i++){
if(i !== col && m[row * 3 + i] === n)
return false;
}
for(var i=0;i<3;i++){
if(i !== row && m[col + 3 * i] === n)
return false;
}
return true;
};
var resetTable = function(){
for(var i = 0; i<9; i++){
m[i] = -1;
document.getElementById("c"+i).style.border = "1px solid grey";
}
};
resetTable();
for(var i = 0; i<9; i++){
var val = document.getElementById("i"+i).value;
if(val){
d = parseInt(val);
if(isNaN(d)){
gotoError(i);
return;
}
c = i%3;
r = Math.floor(i/3);
if(!checkField(d,r,c)){
gotoError(i);
return;
}
m[i] = d;
}
}
for(var i=0;i<9;i++){
if(m[i] === -1){
for(var j = 1;j<6;j++){
c = i%3;
r = Math.floor(i/3);
if(checkField(j,r,c)){
document.getElementById("i"+i).value = j;
m[i] = j
break;
}
}
}
}
}
window.addEventListener('submit', function(ev) {
ev.preventDefault();
fillUp();
}, false)
</script>
<style type="text/css">
table {
padding: 1em 1em 1em 1em;
background-color: lightgreen;
}
td {
border: 1px solid grey;
padding: 5px 5px 5px 5px;
margin: 5px 5px 5px 5px;
background-color: lighgrey;
}
input {
width: 1.1em;
height: 1.1em;
text-align:center;
}
</style>
</head>
<body>
<form id="form0">
<table id="table0">
<tr id="r0">
<td id="c0"><input id="i0" maxlength="1" pattern="^[1-5]$"></td>
<td id="c1"><input id="i1" maxlength="1" pattern="^[1-5]$"></td>
<td id="c2"><input id="i2" maxlength="1" pattern="^[1-5]$"></td>
</tr>
<tr id="r1">
<td id="c3"><input id="i3" maxlength="1" pattern="^[1-5]$"></td>
<td id="c4"><input id="i4" maxlength="1" pattern="^[1-5]$"></td>
<td id="c5"><input id="i5" maxlength="1" pattern="^[1-5]$"></td>
</tr>
<tr id="r2">
<td id="c6"><input id="i6" maxlength="1" pattern="^[1-5]$"></td>
<td id="c7"><input id="i7" maxlength="1" pattern="^[1-5]$"></td>
<td id="c8"><input id="i8" maxlength="1" pattern="^[1-5]$"></td>
</tr>
</table>
<button id="bt0" type="button" onclick="fillUp()">Fill Up</button>
<button id="bt1" type="button" onclick="clearTable()">Clear Table</button>
<form>
</body>
</html>

Categories

Resources