O Connor
O Connor

Reputation: 4402

How to set focus on textarea which is rendered inside v-for in Vuejs 2?

In my Vue.js component, I rendered table rows containing textarea based on a list of items as following:

<template>
    <div>
       <table>
           <tr v-for="(item, index) in items">
               <td>{{ index }}</td>
               <td><textarea v-model="item.message"></textarea></td>
           </tr>
       </table>
    </div>
</template>
<script>
    export default {
        data: {
            items: [
               { message: 'Foo' },
               { message: 'Bar' }
            ]
        }
    };
</script>

When I click anywhere in a row, I want the textarea inside that row to be focused. How can I do that?

The following code cannot solve the problem:

 this.$refs.myTextArea.focus();

This only works with element with unique ref id and outside of v-for.

Upvotes: 2

Views: 4663

Answers (2)

avcajaraville
avcajaraville

Reputation: 9084

Have you tried adding a dynamic value for ref on each row?

Then you can react to click events and select the proper textarea based on that attribute.

Something like:

<template>
    <div>
       <table>
           <tr v-for="(item, index) in items" v-on:click="focusTextArea(index)">
               <td>{{ index }}</td>
               <td>
                 <textarea ref="textArea{{index}}" v-model="item.message"></textarea>
               </td>
           </tr>
       </table>
    </div>
</template>
<script>
    export default {
        data: {
            items: [
               { message: 'Foo' },
               { message: 'Bar' }
            ]
        },
        methods: {
          focusTextArea: (textAreaIndex) => {
            this.$refs[`textArea{textAreaIndex}`].$el.focus();
          }
        }
    };
</script>

Upvotes: 1

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

Try to specify an unique ref name to each text area like :

    <tr v-for="(item, index) in items" @click="focus('ta'+index)">
               <td>{{ index }}</td>
               <td><textarea v-model="item.message" :ref="'ta'+index"></textarea></td>
           </tr>

focus method :

methods:{
  focus(key){
    this.$refs[key][0].focus()
   }
}

check this demo

Upvotes: 2

Related Questions