3

I am new to Vue and it's my first project on Vue as well. I have three input fields which contains on empty values. Is there a way to move on to second input field automatically or make it select, if the input field 1 receives more than 5 characters? And move on to input field 3 or select input field 3 if input field 2 contains more than 5 characters ?

View

<div id="app">
  <h2>Input Fields:</h2>
  <div v-for="(todo,index) in todos" :key="index">

   <b-form-input type="text" v-model="todo.datatype" :value="todo.id" placeholder="Insert Datatype"
   v-on:input="moveToNextField($event)"></b-form-input>

   /** If the input field 1, consists more than 5 characters. Automatically move on to second input field **/

   <br>
  </div>
</div>

Script

new Vue({
  el: "#app",
  data: {
    todos: [
      { id: "1", datatype: ""},
      { id: "2", datatype: ""},
      { id: "3", datatype: ""}
    ]
  },
  methods: {
    toggle: function(todo){
        todo.done = !todo.done
    },

    moveToNextField(event){

        if(this.todos[0].datatype.length > 2)
          {
            console.log("field 1");
          }

      if(this.todos[1].datatype.length > 2)
          {
            console.log("field 2");
          }

    }

  }
})

Below is my code uploaded on JsFiddle

https://jsfiddle.net/ujjumaki/dpbojx0e/36/

Phil
  • 157,677
  • 23
  • 242
  • 245
Yahoo
  • 558
  • 11
  • 34

1 Answers1

5

First things first, you shouldn't be using both v-model and :value on the same element / component. I'll assume you just want to bind the input to each todo.datatype.

You can assign a ref attribute to your inputs which, because they're in a v-for iterator, will create an array in your component's $refs property.

You can then use that to control focus.

For example

new Vue({
  el: "#app",
  data: {
    todos: [
      { id: "1", datatype: "" },
      { id: "2", datatype: "" },
      { id: "3", datatype: "" }
    ]
  },
  methods: {
    moveToNextField(value, index) {
      const nextIndex = index + 1
      if (nextIndex < this.todos.length && value.length > 5) {
        this.$refs.todos[nextIndex].focus()
      }
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<div id="app">
  <h2>Input Fields:</h2>
  <div v-for="(todo, index) in todos" :key="todo.id">
    <input 
      type="text" 
      v-model="todo.datatype" 
      placeholder="Insert Datatype" 
      ref="todos" 
      @input="moveToNextField($event.target.value, index)">
    <br>
  </div>
</div>

The above will work fine with BootstrapVue as well.

Phil
  • 157,677
  • 23
  • 242
  • 245
  • For bootstrap-vue use `@input="moveToNextField($event, index)"` instead of `@input="moveToNextField($event.target.value, index)"` – code.cycling Nov 05 '21 at 12:48