Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Move to previous input on keydown using javascript

I want to move to the next inputbox with javascript whenevever the maxlength of an inputbox is reached.
When the backspace key is pressed I want to clear the current inputbox and move to the previous one.

This is kind of working. Except whenever I press the backspace key it goes to the previous inputbox but doesn’t clear the one I was currently on.

Example;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var elts = document.getElementsByClassName('test')
Array.from(elts).forEach(function(elt){
  elt.addEventListener("keydown", function(event) {
    // Number 13 is the "Enter" key on the keyboard
    if (event.keyCode === 13 || elt.value.length == 1) {
      // Focus on the next sibling
      elt.nextElementSibling.focus()
    }
    if( event.keyCode == 8)
      {
        if (elt.previousElementSibling != null)
        {
            elt.previousElementSibling.focus();
        }
      }
  });
})
body {
    margin: 1em;
}

.field {
    margin-bottom: 1em;
}
<input type="text" class="test" id="0" maxlength="1"/>
<input type="text" class="test" id="1" maxlength="1"/>
<input type="text" class="test" id="2" maxlength="1"/>
<input type="text" class="test" id="3" maxlength="1"/>

>Solution :

Try

var elts = document.getElementsByClassName('test')
Array.from(elts).forEach(function(elt) {
  elt.addEventListener("keydown", function(event) {
    // Number 13 is the "Enter" key on the keyboard
    if (event.keyCode === 13 ||
        event.keyCode !== 8 && elt.value.length === Number(elt.maxLength)
    ) {
      // Focus on the next sibling
      elt.nextElementSibling.focus()
    }
    if (event.keyCode == 8) {
      elt.value = '';
      if (elt.previousElementSibling != null) {
        elt.previousElementSibling.focus();
        event.preventDefault();
      }
    }
  });
})
body {
  margin: 1em;
}

.field {
  margin-bottom: 1em;
}
<input type="text" class="test" id="0" maxlength="1" />
<input type="text" class="test" id="1" maxlength="1" />
<input type="text" class="test" id="2" maxlength="1" />
<input type="text" class="test" id="3" maxlength="1" />
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading