Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting text in a textField with Vuetify

I'm trying to dynamically set the value of a text field in Vuetify, focus it and selecting its text (in order for the user to be able to quickly reset the field if necessary). The error I get is "select is not a function". This works for normal text inputs, but does not with Vuetify text fields.

<template>
    <vContainer>
        <vTextField
            ref="input"
            v-model="input"
        />
        <vBtn
            @click="test"
        >
            Select
        </vBtn>
    </vContainer>
</template>

<script>

export default {
    data: () => ({
        input: null,
    }),

    methods: {
        test() {
            this.input = 'test value';
            this.$refs.input.focus();
            // this.$refs.input.select(); -> TypeError: this.$refs.input.select is not a function
        },
    },
};

</script>
like image 769
Pascal Gremaud Avatar asked Dec 07 '22 10:12

Pascal Gremaud


2 Answers

An easy trick to select text in text field:

<v-text-field
    v-model="inputModel"
    @focus="$event.target.select()"
></v-text-field>
like image 149
icl7126 Avatar answered Jan 07 '23 16:01

icl7126


The problem is that this.$refs.input is not the underlying HTML input element. To get the input element do something like...

let inputEl = this.$refs.input.$el.querySelector('input')

Also, setting the this.input value and then attempting to immediately focus() and select() will not work. You'd need to use nextTick or setTimeout before attempting to select(). For example:

  test() {
        let inputEl = this.$refs.input.$el.querySelector('input')
        this.input = 'test value'
        setTimeout(()=>{
            inputEl.select()
        },200)
  },

Demo

like image 24
Zim Avatar answered Jan 07 '23 18:01

Zim