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
<html>
<body>
<div id='lock'></div>
<script>
const lock = document.getElementById('lock')
function makeLockDigit(changeCallback) {
// Make an input that can be set between 0 and 9.
// This is equivalent to <input type='number' min='0' max='9' />.
const digit = document.createElement('input')
digit.type = 'number'
digit.min = 0
digit.max = 9
// Start it with a random value
digit.value = String(Math.floor(Math.random() * 10))
// When the digit changes, call `changeCallback()`,
// passing the new value of the digit.
// Inputs' values are strings, so we convert them to numbers.
digit.addEventListener('change', () => {
changeCallback(Number(digit.value))
})
// Add the digit to the lock
lock.appendChild(digit)
}
// The super secret combination
const COMBO = [1, 2, 3, 4]
// Whether each digit is correct
const digitCorrect = [false, false, false, false]
for (let i = 0; i < 4; i++) {
makeLockDigit(value => {
// Digit i has changed, so store whether it is correct
digitCorrect[i] = (value === COMBO[i])
// If all digits are now correct, show a message
if (digitCorrect.every(correct => correct)) {
alert('You got the combination')
}
})
}
</script>
</body>
</html>