Quantcast
Channel: Active questions tagged html - Stack Overflow
Viewing all articles
Browse latest Browse all 67411

@keydown and @input firing together

$
0
0

I am working on a component in a vue application that takes a passcode that is 8 digits each digit has its own input when types a character in, it should move to the next input, if the user deletes the character if it can the focus should move to the previous sibling, if the user presses the left or right key, the focus should move with the key press. What is happening at the moment is that the @input and @keydown event are both firing, so if the the user presses left and the the previous sibling already has content, it moves the focus back to the right.

Here is my code,

<div class="code">
  <input autofocus type="text" maxlength="1" class="passcode__box" @input="handleInput" @keydown="handleKeyDown"/>
  <input type="text" class="passcode__box" maxlength="1" @input="handleInput" @keydown="handleKeyDown"/>
  <input type="text" class="passcode__box" maxlength="1" @keyup="handleInput" @keydown="handleKeyDown"/>
  <input type="text" class="passcode__box" maxlength="1" @keyup="handleInput" @keydown="handleKeyDown"/>
  <input type="text" class="passcode__box" maxlength="1" @keyup="handleInput" @keydown="handleKeyDown"/>
  <input type="text" class="passcode__box" maxlength="1" @keyup="handleInput" @keydown="handleKeyDown"/>
  <input type="text" class="passcode__box" maxlength="1" @keyup="handleInput" @keydown="handleKeyDown"/>
  <input type="text" class="passcode__box" maxlength="1" @keyup="handleInput" @keydown="handleKeyDown"/>
</div>

and the 2 methods,

handleInput(event) {
  const value = event.target.value;
  const nextElement = event.target.nextElementSibling;
  if (value === "" || !nextElement) {
    return;
  }
  nextElement.focus();

},

  handleKeyDown(event) {
    console.log('handleKeyDown');
    //Right arrow key
    if(event.keyCode == 39) {
      event.target.nextElementSibling.focus();
    }

    //Left arrow key
    if(event.keyCode == 37) {
      event.target.previousElementSibling.focus();
    }

    //Backspace key - cmd
    if(event.keyCode == 8) { //backspace
      if(event.target.value === '') {
        event.target.previousElementSibling.focus();
        return;
      }
      event.target.value = '';
    }
  }

Here is an example of the component, that wierdly uses the same code enter link description here


Viewing all articles
Browse latest Browse all 67411

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>