2

I have a form where user can fill an email address and click a plus button against it to create a new one. These input boxes are generated by iterating over an array. When user clicks on the + icon, a new entry is pushed to this array.

Now the new text box is generating fine but I want the cursor to be focused in this one.

enter image description here

1
  • 1
    can you please share your code? Commented Jan 15, 2020 at 10:19

2 Answers 2

8

as @ramakant-mishra told you must use this.$refs, but you need to add ref attribute dynamically on your input element also. let me show you:

new Vue({
  el: '#app',
  data: {
    emails:[]
  },
  methods: {
    add: function (e) {
      let j = this.emails.push("")
      this.$nextTick(() => {
        this.$refs[`email${j - 1}`][0].focus()
      })
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="(email, i) in emails" :key="i">
    <input v-model="email" :ref="`email${i}`" />
  </div>
  <button @click="add">add</button>
</div>

just don't forget to use $nextTick because the new element is not rendered yet on template

Sign up to request clarification or add additional context in comments.

Comments

4

They key is to set ref on all your inputs to the same string like this:

<input type="text" ref="myInputs"/>

Then you will have access to an array called this.$refs.myInputs inside an event handler.

new Vue({
  el: "#app",

  data() {
    return {
      emails: []
    };
  },
  
  methods: {
    addEmail() {
      this.emails.push('whatever');
      this.$nextTick(() => {
          const lastIdx = this.emails.length - 1;
          this.$refs.myInputs[lastIdx].focus();
      });
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>

<div id="app">
  <input type="button" @click="addEmail()" value="Add Email"/>
  <div v-for="(email, index) in emails" :key="index">
    <input ref="myInputs" type="text" />
  </div>
</div>

Note that below you must put the call to focus() inside a nextTick() in order to give Vue a chance to actually render the email you just added to the list.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.