Vanilla JavaScript calculator - javascript

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;

Related

Javascript Interval continues endless without conditions met

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>

Replaces Value in the first row

I really need help in my add to cart function. The problem is that when i added product in the shopping cart the second time, it replaces the value in the first. It should be displayed in another row. Please help me. Thanks.
var qtyTotal = 0;
var priceTotal = 0;
var products = [];
function addProduct() {
var productID = document.getElementById("productID").value;
var product_desc = document.getElementById("product_desc").value;
var qty = document.getElementById("quantity").value;
// qtyTotal = qtyTotal + parseInt(qty);
//document.getElementById("qtyTotals").innerHTML=qtyTotal;
var price = document.getElementById("price").value;
var newProduct = {
product_id : null,
product_desc : null,
product_qty : 0,
product_price : 0.00,
};
newProduct.product_id = productID;
newProduct.product_desc = product_desc;
newProduct.product_qty = qty;
newProduct.product_price = price;
products.push(newProduct);
//console.log("New Product " + JSON.stringify(newProduct))
//console.log("Products " + JSON.stringify(products))
var html = "<table border='1|1' >";
html+="<td>Product ID</td>";
html+="<td>Product Description</td>";
html+="<td>Quantity</td>";
html+="<td>Price</td>";
html+="<td>Action</td>";
for (var i = 0; i < products.length; i++) {
html+="<tr>";
html+="<td>"+products[i].product_id+"</td>";
html+="<td>"+products[i].product_desc+"</td>";
html+="<td>"+products[i].product_qty+"</td>";
html+="<td>"+products[i].product_price+"</td>";
html+="<td><button type='submit' onClick='deleteProduct(\""+products[i].product_id +"\", this);'/>Delete Item</button> &nbsp <button type='submit' onClick='addCart(\""+products[i].product_id +"\", this);'/>Add to Cart</button></td>";
html+="</tr>";
}
html+="</table>";
document.getElementById("demo").innerHTML = html;
document.getElementById("resetbtn").click()
}
function deleteProduct(product_id, e) {
e.parentNode.parentNode.parentNode.removeChild(e.parentNode.parentNode);
for(var i = 0; i < products.length; i++) {
if (products[i].product_id == product_id) {
// DO NOT CHANGE THE 1 HERE
products.splice(i, 1);
}
}
}
function addCart(product_id){
var html = "<table border='1|1'>";
html+="<td>Product ID</td>";
html+="<td>Product Description</td>";
html+="<td>Quantity</td>";
html+="<td>Price</td>";
html+="<td>Total</td>";
html+="<td>Action</td>";
for (var i = 0; i < products.length; i++) {
if (products[i].product_id == product_id) {
products[i].product_qty = parseInt(products[i].product_qty) + 1;
html+="<tr>";
html+="<td>"+products[i].product_id+"</td>";
html+="<td>"+products[i].product_desc+"</td>";
html+="<td>"+products[i].product_qty+"</td>";
html+="<td>"+products[i].product_price+"</td>";
html+="<td>"+parseInt(products[i].product_price)*parseInt(products[i].product_qty)+"</td>";
html+="<td><button type='submit' onClick='subtractQuantity(\""+products[i].product_id +"\", this);'/>Subtract Quantity</button></td>";
html+="</tr>";
}
}
html+="</table>";
document.getElementById("demo2").innerHTML = html;
}
function subtractQuantity(product_id)
{ alert(product_id);
for(var i = 0; i < products.length; i++) {
if (products[i].product_id == product_id & products[i].product_qty >= 1) {
products[i].product_qty = parseInt(products[i].product_qty) - 1;
}
if (products[i].product_id == 0) {
removeItem(products[i].product_id);
}
console.log("Products " + JSON.stringify(products));
}
}
function removeItem(product_id) {
for(var i = 0; i < products.length; i++) {
if (products[i].product_id == product_id) {
// DO NOT CHANGE THE 1 HERE
products.splice(i, 1);
}
}
}
<!DOCTYPE html>
<html>
<head>
<title>Shopping Cart Pure Javascript</title>
</head>
<body>
<form name="order" id="order">
<table>
<tr>
<td>
<label for="productID">Product ID:</label>
</td>
<td>
<input id="productID" name="product" type="text" size="28" required/>
</td>
</tr>
<tr>
<td>
<label for="product">Product Desc:</label>
</td>
<td>
<input id="product_desc" name="product" type="text" size="28" required/>
</td>
</tr>
<tr>
<td>
<label for="quantity">Quantity:</label>
</td>
<td>
<input id="quantity" name="quantity" width="196px" required/>
</td>
</tr>
<tr>
<td>
<label for="price">Price:</label>
</td>
<td>
<input id="price" name="price" size="28" required/>
</td>
</tr>
</table>
<input type="reset" name="reset" id="resetbtn" class="resetbtn" value="Reset" />
<input type="button" id="btnAddProduct" onclick="addProduct();" value="Add New Product" >
</form>
<br>
<p id="demo"></p> <br/>
<h2> Shopping Cart </h2>
<p id="demo2"></p>
</body>
</html>
Check below code. I have change it with javascript.
var qtyTotal = 0;
var priceTotal = 0;
var products = [];
function addProduct() {
var productID = document.getElementById("productID").value;
var product_desc = document.getElementById("product_desc").value;
var qty = document.getElementById("quantity").value;
// qtyTotal = qtyTotal + parseInt(qty);
//document.getElementById("qtyTotals").innerHTML=qtyTotal;
var price = document.getElementById("price").value;
var newProduct = {
product_id : null,
product_desc : null,
product_qty : 0,
product_price : 0.00,
};
newProduct.product_id = productID;
newProduct.product_desc = product_desc;
newProduct.product_qty = qty;
newProduct.product_price = price;
products.push(newProduct);
//console.log("New Product " + JSON.stringify(newProduct))
//console.log("Products " + JSON.stringify(products))
var html = "<table border='1|1' >";
html+="<td>Product ID</td>";
html+="<td>Product Description</td>";
html+="<td>Quantity</td>";
html+="<td>Price</td>";
html+="<td>Action</td>";
for (var i = 0; i < products.length; i++) {
html+="<tr>";
html+="<td>"+products[i].product_id+"</td>";
html+="<td>"+products[i].product_desc+"</td>";
html+="<td>"+products[i].product_qty+"</td>";
html+="<td>"+products[i].product_price+"</td>";
html+="<td><button type='submit' onClick='deleteProduct(\""+products[i].product_id +"\", this);'/>Delete Item</button> &nbsp <button type='submit' onClick='addCart(\""+products[i].product_id +"\", this);'/>Add to Cart</button></td>";
html+="</tr>";
}
html+="</table>";
document.getElementById("demo").innerHTML = html;
document.getElementById("resetbtn").click()
}
function deleteProduct(product_id, e) {
e.parentNode.parentNode.parentNode.removeChild(e.parentNode.parentNode);
for(var i = 0; i < products.length; i++) {
if (products[i].product_id == product_id) {
// DO NOT CHANGE THE 1 HERE
products.splice(i, 1);
}
}
}
function addCart(product_id){
var html = '';
var ele = document.getElementById("demo2");
if(ele.innerHTML == '')
{
html+="<table id='tblCart' border='1|1'>";
html+="<tr><td>Product ID</td>";
html+="<td>Product Description</td>";
html+="<td>Quantity</td>";
html+="<td>Price</td>";
html+="<td>Total</td>";
html+="<td>Action</td></tr>";
}
for (var i = 0; i < products.length; i++) {
if (products[i].product_id == product_id) {
products[i].product_qty = parseInt(products[i].product_qty) + 1;
html+="<tr>";
html+="<td>"+products[i].product_id+"</td>";
html+="<td>"+products[i].product_desc+"</td>";
html+="<td>"+products[i].product_qty+"</td>";
html+="<td>"+products[i].product_price+"</td>";
html+="<td>"+parseInt(products[i].product_price)*parseInt(products[i].product_qty)+"</td>";
html+="<td><button type='submit' onClick='subtractQuantity(\""+products[i].product_id +"\", this);'/>Subtract Quantity</button></td>";
html+="</tr>";
}
}
if(ele.innerHTML == '')
{
html+= "</table>";
ele.innerHTML = html;
}
else
{
document.getElementById("tblCart").innerHTML += html;
}
}
function subtractQuantity(product_id)
{ alert(product_id);
for(var i = 0; i < products.length; i++) {
if (products[i].product_id == product_id & products[i].product_qty >= 1) {
products[i].product_qty = parseInt(products[i].product_qty) - 1;
}
if (products[i].product_id == 0) {
removeItem(products[i].product_id);
}
console.log("Products " + JSON.stringify(products));
}
}
function removeItem(product_id) {
for(var i = 0; i < products.length; i++) {
if (products[i].product_id == product_id) {
// DO NOT CHANGE THE 1 HERE
products.splice(i, 1);
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Shopping Cart Pure Javascript</title>
</head>
<body>
<form name="order" id="order">
<table>
<tr>
<td>
<label for="productID">Product ID:</label>
</td>
<td>
<input id="productID" name="product" type="text" size="28" required/>
</td>
</tr>
<tr>
<td>
<label for="product">Product Desc:</label>
</td>
<td>
<input id="product_desc" name="product" type="text" size="28" required/>
</td>
</tr>
<tr>
<td>
<label for="quantity">Quantity:</label>
</td>
<td>
<input id="quantity" name="quantity" width="196px" required/>
</td>
</tr>
<tr>
<td>
<label for="price">Price:</label>
</td>
<td>
<input id="price" name="price" size="28" required/>
</td>
</tr>
</table>
<input type="reset" name="reset" id="resetbtn" class="resetbtn" value="Reset" />
<input type="button" id="btnAddProduct" onclick="addProduct();" value="Add New Product" >
</form>
<br>
<p id="demo"></p> <br/>
<h2> Shopping Cart </h2>
<p id="demo2"></p>
</body>
</html>
document.getElementById("demo2").innerHTML = html;
Every time, that function is being called, you are changing the innerHTML of of 'demo2' whereas what you need to do is append to it. Use
document.getElementById("demo2").innerHTML += html;
Also, it is not a good idea to use the innerHTML property.It destroys references thus killing eventListeners or similar stuff linked to the object. Hope it helps !

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>

HTML, CSS, javascript calculator

Im having problems with my calculator. The buttons work and all align right but I can't get anything to show up on the monitor box or calculate anything. I listed my code below can anyone help me find where I went wrong? I feel it has to do with the true or false but I can't figure it out.
Here is the HTML code:
<body>
<table>
<tr>
<input id="display" type="text" value="0"/><span id="currOp"></span>
<tr>
<td>
<button id="7" class="num">7</button>
</td>
<td>
<button id="8" class="num">8</button>
</td>
<td>
<button id="9" class="num">9</button>
</td>
<td>
<button id="plus" class="operator">+</button>
</td>
<td>
<button id="clear">C</button>
</td>
</tr>
<tr>
<td>
<button id="4" class="num">4</button>
</td>
<td>
<button id="5" class="num">5</button>
</td>
<td>
<button id="6" class="num">6</button>
</td>
<td>
<button id="minus" class="operator">-</button>
</td>
<td>
<button id="root">√</button>
</td>
</tr>
<tr>
<td>
<button id="1" class="num">1</button>
</td>
<td>
<button id="2" class="num">2</button>
</td>
<td>
<button id="3" class="num">3</button>
</td>
<td>
<button id="mult" class="operator">x</button>
</td>
<td>
<button id="power" class="operator">x^y</button>
</td>
</tr>
<tr>
<td>
<button id="0" class="num">0</button>
</td>
<td>
<button id="decimal">.</button>
</td>
<td>
<button id="invert">±</button>
</td>
<td>
<button id="divid" class="operator">÷</button>
</td>
<td>
<button id="equals">=</button>
</td>
</tr>
Here is the CSS code:
button {
height: 40px;
width: 40px;
font-size: 110%;
}
#display{
font-size: 120%;
text-align: right;
}
span {
font-size: 150%;
}
and here is the javascript code:
var isOperating = true;
var isfloating = false;
var toBeCleared = true;
var operator;
var operand;
var display;
$(document).ready(init);
function init() {
display = $('#display');
$('.num').on('click', numClicked);
$('.operator').on('click', operatorClicked);
$('#invert').on('click', invertClicked);
$('#root').on('click', rootClicked);
$('#decimal').on('click', decimalClicked);
$('#equals').on('click', equalsClicked);
$('#clear').on('click', clearClicked);
}
function numClicked() {
var currVal = display.val();
var clickedNum = $(this).text();
if (currVal === "0" || toBeCleared) {
toBeCleared = true;
display.val(clickedNum);
} else {
display.val(currVal + clickedNum);
}
}
function invertClicked() {
display.val(display.val() * -1);
}
function rootClicked() {
display.val(Math.sqrt(evaluate()));
}
function decimalClicked() {
if (toBeCleared) {
display.val('0.');
toBeCleared = true;
} else {
if (!isFloating) {
display.val(display.val().concat('.'));
}
}
isFloating = false;
}
function equalsClicked() {
display.val(evaluate());
reset();
}
function clearClicked() {
reset();
display.val('0');
}
function reset() {
toBeCleared = true;
isOperating = true;
isFloating = false;
operator = null;
operand = null;
$('#currOp').text('');
}
function operatorClicked() {
if (isOperating) {
display.val(evaluate());
}
switch ($(this).attr('id')) {
case 'plus': operator = '+'; break;
case 'minus': operator = '-'; break;
case 'mult': operator = 'x'; break;
case 'divide': operator = '÷'; break;
case 'power': operator = '^'; break;
}
operand = parseFloat(display.val());
isOperating = true;
toBeCleared = true;
$('#currOp').text(operator);
}
function evaluate() {
`enter code here` var currVal = parseFloat(display.val());
var result;
switch (operator) {
case '+': result = operand + currVal; break;
case '-': result = operand - currVal; break;
case 'x': result = operand * currVal; break;
case '÷':
if (currVal === 0) {
result = 'Err';
} else {
result = operand / currVal;
}
break;
case '^': result = Math.pow(operand, currVal); break;
default: result = currVal;
}
return result;
}
You should set toBeCleared = false;
if (currVal === "0" || toBeCleared) {
toBeCleared = false;
display.val(clickedNum);
} else {
display.val(currVal + clickedNum);
}

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