lock1.html 1.39 KB
<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.onchange = () => 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 < COMBO.length; 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>