Vue JS focus next input on enter Vue JS focus next input on enter vue.js vue.js

Vue JS focus next input on enter


You can try something like this:

<input v-on:keyup.enter="$event.target.nextElementSibling.focus()" type="text">

JSfiddle Example

Update

In case if the target element is inside form element and next form element is not a real sibling then you can do the following:

html

<form id="app">  <p>{{ message }}</p>  <input v-on:keyup.enter="goNext($event.target)" type="text">    <div>      <input type="text">  </div></form>

js

new Vue({  el: '#app',  data: {    message: 'Hello Vue.js!',    focusNext(elem) {      const currentIndex = Array.from(elem.form.elements).indexOf(elem);      elem.form.elements.item(        currentIndex < elem.form.elements.length - 1 ?        currentIndex + 1 :        0      ).focus();    }  }})

JSFiddle Example


Following up from @zurzui here is in my opinion a cleaner alternative using the $refs API (https://vuejs.org/v2/api/#vm-refs).

Using the $refs API, can allow you to target element in a simpler fashion without traversing the DOM.

Example: https://jsfiddle.net/xjdujke7/1/


After some tests, it's working

new Vue({    el:'#app',    methods: {      nextPlease: function (event) {        document.getElementById('input2').focus();      }    }});
<script src="https://vuejs.org/js/vue.js"></script><div id='app'>    <input type="text" v-on:keyup.enter="nextPlease">    <input id="input2" type="text"></div>