Home > OS >  How to get selectionStart and selectionEnd properties of v-textarea in VueJS?
How to get selectionStart and selectionEnd properties of v-textarea in VueJS?

Time:01-09

I know you can get the startSelection and selectionEnd properties of normal <textarea> by using DOM or $refs in VueJS.

I however am struggling to accomplish the same thing with <v-textarea>. I have googled around and most things either use normal JS with <textarea> or VueJS but also with <textarea>.

Sample Code:

 <v-textarea
            :value="value"
            :label="label"
            hide-details="auto"
            :name="name"
            auto-grow
            no-resize
            clearable
            rows="1"
            @input="emitSelectedPositons"
            :error-messages="errorMessages"
            ref="vta"
/>

...

<script>
  ....
  methods: {
      emitSelectedPositons() {
          this.$emit('changed', {
              start: this.$refs.vta.selectionStart,
              end: this.$refs.vta.selectionEnd
          })
      }
  }
</script>

The code above returns undefined for both.

CodePudding user response:

$refs.vta only returns the v-textarea element, which is a wrapper element containing its own refs which includes the inner <textarea> input element. You can access the inner element to get selectionStart and selectionEnd like so:

this.start = this.$refs.vta.$refs.input.selectionStart;
this.end = this.$refs.vta.$refs.input.selectionEnd;

sandbox example

  • Related