Search code examples
javascriptfocusvue.js

Vue JS focus next input on enter


I have 2 inputs and want switch focus from first to second when user press Enter. I tried mix jQuery with Vue becouse I can't find any function to focus on something in Vue documentation:

<input v-on:keyup.enter="$(':focus').next('input').focus()"
    ...>
<input  ...>

But on enter I see error in console:

build.js:11079 [Vue warn]: Property or method "$" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option. (found in anonymous component - use the "name" option for better debugging messages.)warn @ build.js:11079has @ build.js:9011keyup @ build.js:15333(anonymous function) @ build.js:10111
build.js:15333 Uncaught TypeError: $ is not a function

Solution

  • 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