Search code examples
javascriptfocustypeerrorundefined

Uncaught TypeError: Cannot read properties of undefined (reading 'focus')


UI Screenshot

When I input 6 digit of verification code then it shows

Uncaught TypeError: Cannot read properties of undefined (reading 'focus')

The verification code not coming from the server. It's just normal javaScript code for frontend UI

let codes = document.querySelectorAll('.code')

codes[0].focus()

codes.forEach(function (code, idx) {
    code.addEventListener('keydown', function (e) {
        if (e.key >= 0 && e.key <= 9) {
            codes[idx].value = ''
            setTimeout(() => codes[idx + 1].focus(), 10)
        } else if (e.key === 'Backspace') {
            setTimeout(() => codes[idx - 1].focus(), 10)
        }
    })
})

What should i use in the javaScript sothat the error will solve


Solution

  • It means that either codes[idx + 1] or codes[idx - 1] is an index that doesn't exist and returns undefined. You can add a check before you calling the focus method.

    setTimeout(() => {
      if (typeof codes[idx + 1] !== 'undefined') {
        codes[idx + 1].focus()
      }
    }, 10)
    

    Or you can use the optional chaining operator ?. to shorten it.

    setTimeout(() => codes[idx + 1]?.focus(), 10)