Search code examples
javascriptfocusgetelementbyidgetelementsbyclassname

Javascript to move focus onkeyup getElementById Works getElementsByClassName does not


I am trying to move the focus from one input field to the next one once the key is pressed. For some reason it works when I am using getElementById but when I am changing it to getElementByClassName it does not.

Works:

<input id="char1" type="text" maxlength="1" onkeyup="document.getElementById('char2').focus()" />
<input id="char2" type="text" maxlength="1" onkeyup="document.getElementById('char3').focus()" />
<input id="char3" type="text" maxlength="1" onkeyup="document.getElementById('char1').focus()" />

Does not work:

<input class="char1" type="text" maxlength="1" onkeyup="document.getElementsByClassName('char2').focus()" />
<input class="char2" type="text" maxlength="1" onkeyup="document.getElementsByClassName('char3').focus()" />
<input class="char3" type="text" maxlength="1" onkeyup="document.getElementsByClassName('char1').focus()" />

Solution

  • That's because classes are retrieved as arrays so you have to access it by index and also you did an error it's document.getElementsByClassName not Element.

    <input class="char1" type="text" maxlength="1" onkeyup="document.getElementsByClassName('char2')[0].focus()" />
    <input class="char2" type="text" maxlength="1" onkeyup="document.getElementsByClassName('char3')[0].focus()" />
    <input class="char3" type="text" maxlength="1" onkeyup="document.getElementsByClassName('char1')[0].focus()" />