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>
Related
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=" « " 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=" « " 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>
<!DOCTYPE html>
<html <head>
<meta charset="utf-8">
<title>Credit Card Number Validator</title>
<style>
<!-- .title {
font-family: "Trebuchet MS";
font-size: 30px;
font-style: oblique;
color: #006600;
text-align: center;
}
body {
background-color: #FFFFE8;
font-family: Arial, Helvetica, sans-serif;
}
table {
margin: auto;
width: 600px;
}
.right {
text-align: right;
}
.center {
text-align: center;
}
#id {
width: 175px;
}
-->
</style>
</head>
<body>
<p class="title">Validate a credit card number </p>
<form name="form1" id="form1" method="post" action="">
<table>
<tr>
<td width="219" class="right">Enter the credit card number:</td>
<td width="168" class="center"><input name="textfield" type="text" id="card"></td>
<td width="196" id="output"> </td>
</tr>
<tr>
<td height="30"> </td>
<td class="center"><input type="button" id="button" value="Test the Card Number!"></td>
<td> </td>
</tr>
</table>
</form>
<script>
document.getElementById("button").addEventListener('click', credit, false);
function credit() {
data = document.getElementById("card").value;
if (data) {
cardnum = data.replace(/[^0-9]/, "");
} else {
alert('Please enter a number to test.');
}
if (cardnum.length == 16 && cardnum.charAt(0) == "5" && cardnum.charAt(1) != "0" && cardnum.charAt(12) == "7") {
donecard = +cardnum.substr(0, 3) + " ";
document.getElementById("card").innerHTML = donecard;
document.getElementById("output").innerHTML = "valid";
} else {
document.getElementById("output").innerHTML = "invalid";
}
}
</script>
</body>
</html>
I'm trying to implement the Luhn algorithm to my code, so that it works together.
My first block works well it validates numbers correctly based off the code. This block works correctly. I want to implement the second part to it, which is the luhn algorithim with a loop or loops. What would be the best way to do this.
Something like this might work. Typed from my phone so probably has typos.
let sum = 0;
let len = cardnum.length;
for(let i=0; i = len; i++) {
let foo = cardnum.charAt(len-i)
if(i % 2 ) {
foo = foo * 2;
foo = (foo) > 9) ? foo-9 : foo;
sum = sum + foo;
} else {
sum = sum + foo
}
if( (sum * 9) % 10 === 0) {
console.log(‘valid’)
}
I am trying to add an alert to notify the user that data has already been entered. I want to apply this to the flight number only. So that when a user types in an already typed flight number and saves it into the array it will pop up a message telling them that it has already been posted.
<html>
<head>
<title>Member Info</title>
<style>
table, th, td {
border: 1px solid black;
text-align: center;
border-collapse: collapse;
}
</style>
<script type="text/javascript">
var FlightNumber=new Array();
var Miles=new Array();
function insert(){
var FlightNumberValue = document.getElementById('FlightNumber').value;
var MilesValue = document.getElementById('Miles').value;
FlightNumber[FlightNumber.length]=FlightNumberValue;
Miles[Miles.length]=MilesValue;
}
function showFlightNumber() {
var content="<b></b><br>";
for(var i = 0; i < FlightNumber.length; i++) {
content +=FlightNumber[i]+"<br>";
}
document.getElementById('display').innerHTML = content;
}
function showMiles() {
var content="<b></b><br>";
for(var i = 0; i < Miles.length; i++) {
content +=Miles[i]+"<br>";
}
document.getElementById('display2').innerHTML = content;
// new code
var total=0;
for(var i = 0; i < Miles.length; i++) {
total += Number.parseInt(Miles[i]);
}
document.getElementById('total-miles').innerHTML = total;
}
</script>
</head>
<body>
<form id="form">
<h1>Find out what Flight Class Member you are!</h1>
<p>To use, please input the flight number and number of miles. Press save and then show. To enter more than one press "Enter More" button and repeat steps.<p>
<br>
<label for="FlightNumber">Flight Number</label> <input id="FlightNumber" type="text" />
<br>
<label for="Miles">Miles</label><input id="Miles" type="text" />
<br>
<br>
<input type="button" value="Save" onclick="insert();">
<input type="button" value="Show flight number" onclick="showFlightNumber();">
<input type="button" value="Show miles" onclick="showMiles();">
<input type= "reset" value="Enter More" />
<hr>
</form>
<table style="width:100%">
<tr>
<th>Flight Number</th>
<th>Miles</th>
</tr>
<tr>
<td><div id="display">
</div></td>
<td><div id="display2">
</div></td>
</tr>
<td>Total Miles:</td>
<td id="total-miles"></td>
</table>
<br><br>
<table id="MemberTable" style="width:100%", border="1px solid black">
<tr>
<td>Bronze Member</td>
<td><10000 miles flown</td>
</tr>
<tr>
<td>Silver Member</td>
<td><25000 miles flown</td>
</tr>
<tr>
<td>Gold Member</td>
<td>>25000 miles flown</td>
</tr>
</table>
</body>
</html>
I am also trying to highlight the member table to show which group they are in based on total miles. I would like for the color of the highlight to match the member level. Something kind of like this:
<style>
.bronze {
background: rgb(80.4, 49.8, 19.6);
}
.silver {
background: silver
}
.gold {
background: gold
}
</style>
<script>
function highlightWeightClass(total-miles) {
var rows = document.getElementById("MemberTable").rows;
rows[0].className = total-miles< 10000 ? "bronze" : "";
rows[1].className = total-miles >= 10000 && total-miles < 25000 ? "silver" : "";
rows[2].className = total-miles >= 25000 ? "gold" : "";
</script>
For checking if an Array contains on Object, use this:
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] == obj) {
return true;
}
}
return false;
}
For highlighting the member table: add an event listener for document.getElementById("Miles")'s keyup and execute your function then.
<html>
<head>
<title>Member Info</title>
<style>
table, th, td {
border: 1px solid black;
text-align: center;
border-collapse: collapse;
}
.bronze {
background: rgb(80.4, 49.8, 19.6);
}
.silver {
background: silver
}
.gold {
background: gold
}
</style>
<script>
Array.prototype.contains = function(obj) {//function to check if an Array contains an object
var i = this.length;
while (i--) {
if (this[i] == obj) {
return true;
}
}
return false;
}
function highlightWeightClass(totalmiles) {
var rows = document.getElementById("MemberTable").rows;
rows[0].className = totalmiles< 10000 ? "bronze" : "";
rows[1].className = totalmiles >= 10000 && totalmiles < 25000 ? "silver" : "";
rows[2].className = totalmiles >= 25000 ? "gold" : "";
}
</script>
<script type="text/javascript">
var FlightNumber=new Array();
var Miles=new Array();
function insert(){
var FlightNumberValue = document.getElementById('FlightNumber').value;
if(!FlightNumber.contains(FlightNumberValue)){
var MilesValue = document.getElementById('Miles').value;
FlightNumber[FlightNumber.length]=FlightNumberValue;
Miles[Miles.length]=MilesValue;
} else {
alert("You have already entered this flight number.");
}
}
function showFlightNumber() {
var content="<b></b><br>";
for(var i = 0; i < FlightNumber.length; i++) {
content +=FlightNumber[i]+"<br>";
}
document.getElementById('display').innerHTML = content;
}
function showMiles() {
var content="<b></b><br>";
for(var i = 0; i < Miles.length; i++) {
content +=Miles[i]+"<br>";
}
document.getElementById('display2').innerHTML = content;
// new code
var total=0;
for(var i = 0; i < Miles.length; i++) {
total += Number.parseInt(Miles[i]);
}
document.getElementById('total-miles').innerHTML = total;
}
window.onload = function(){
document.getElementById("Miles").addEventListener("keyup", function(event){
highlightWeightClass(document.getElementById("Miles").value);
});
}
</script>
</head>
<body>
<form id="form">
<h1>Find out what Flight Class Member you are!</h1>
<p>To use, please input the flight number and number of miles. Press save and then show. To enter more than one press "Enter More" button and repeat steps.<p>
<br>
<label for="FlightNumber">Flight Number</label> <input id="FlightNumber" type="text" />
<br>
<label for="Miles">Miles</label><input id="Miles" type="text" />
<br>
<br>
<input type="button" value="Save" onclick="insert();">
<input type="button" value="Show flight number" onclick="showFlightNumber();">
<input type="button" value="Show miles" onclick="showMiles();">
<input type= "reset" value="Enter More" />
<hr>
</form>
<table style="width:100%">
<tr>
<th>Flight Number</th>
<th>Miles</th>
</tr>
<tr>
<td><div id="display">
</div></td>
<td><div id="display2">
</div></td>
</tr>
<td>Total Miles:</td>
<td id="total-miles"></td>
</table>
<br><br>
<table id="MemberTable" style="width:100%", border="1px solid black">
<tr>
<td>Bronze Member</td>
<td><10000 miles flown</td>
</tr>
<tr>
<td>Silver Member</td>
<td><25000 miles flown</td>
</tr>
<tr>
<td>Gold Member</td>
<td>>25000 miles flown</td>
</tr>
</table>
</body>
</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>
function table_to_text() {
var j;
var z = '';
var k = 4;
var article1 = new Array();
for (j = 1; j <= k; j++) {
article1[j] = document.getElementById("c" + j).value;
z = z + article1[j];
}
document.getElementById("batch_full").innerText = z;
}
function text_to_table() {
var batch_text = document.getElementById("batch_full").value;
var length_covered = 0;
var n = 4;
var article = new Array();
var temp;
var length;
for (var i = 1; i <= n; i++) {
article[i] = document.getElementById("c" + i);
length = article[i].getAttribute('maxlength');
temp = batch_text.substr(length_covered, length);
article[i].value = temp;
length_covered = Number(length_covered) + Number(length);
}
}
#batch_full {
height: 200px;
width: 500px;
}
table {
border-collapse: collapse;
}
table,
th,
td {
padding: 0px 10px 0px 10px;
}
td {
border: 1px solid black;
}
th {
text-align: left;
text-indent: -2.5%;
}
td>input {
resize: horizontal;
width: 100%;
}
<textarea id="batch_full" onchange="text_to_table()">Batch input here</textarea>
<table id="results_table" onchange="table_to_text()">
<tr>
<th>S.No</th>
<th>Account Number</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
<tr>
<td><input type="text" maxlength="2" id="c1"></td>
<td><input type="text" maxlength="10" id="c2"></td>
<td><input type="text" maxlength="10" id="c3"></td>
<td><input type="text" maxlength="10" id="c4"></td>
</tr>
</table>
<input type="button" onclick="text_to_table()" value="Text to Table">
<input type="button" onclick="table_to_text()" value="Table to Text">
When I enter some text in the element, the changes are reflected in the table elements, but when I try to edit the text in the element, the changes are not reflected in the element.
Please help me in resolving this issue. I'm using Codepen to write this code.
There are no bugs in your code.For instant reflection of your data which you are entering in either Textarea or Table, replace "onchange" event with "oninput" event in the TextArea and table elements and, Since you are using codepen the "innerText" attribute will not be rendered instead use "value" attribute.
That should do the trick.
Change the innterText to innerHTML. Seems to work: http://codepen.io/anon/pen/gLvqMN