-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathluhn.html
51 lines (51 loc) · 1.54 KB
/
luhn.html
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<!DOCTYPE html>
<html>
<head>
<title>Luhn Algorithm</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script>
function luhnAlgo() {
var elText = document.getElementById('txtText');
var elStatus = document.getElementById('spnStatus');
try {
var arr = elText.value.split('');
var len = arr.length;
var cnt = 0;
var one = 0;
var two = 0;
var luhn = '';
var dup = (len % 2 == 0) ? true : false;
for (var ix = 0; ix < len; ix += 1) {
var nn = parseInt(arr[ix]);
if (isNaN(nn) == true) {
throw 'pos=[' + ix + '] ch=[' + arr[ix] + '] is not a digit';
}
if (dup) {
one += nn;
} else {
nn = nn * 2;
if (nn >= 10) {
var ar2 = nn.toString().split('');
nn = parseInt(ar2[0]) + parseInt(ar2[1]);
}
two += nn;
}
dup = ! dup;
cnt = one + two;
luhn = (cnt * 9) % 10;
}
elStatus.innerHTML = elText.value + luhn;
} catch (err) {
elStatus.innerHTML = '[' + elText.value + '] Fail generate check digit.\n' + err;
}
}
</script>
</head>
<body>
<div><a href="https://en.wikipedia.org/wiki/Luhn_algorithm" target="wiki_luhn">Luhn Algorithm</a></div>
<input type="text" id="txtText" onkeyup="luhnAlgo();" value="" />
<br />
<span id="spnStatus"></span>
</body>
</html>