Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS/Vuetify - Add some text to focus position on textarea

I try to add somes text (tags) in Vuetify textarea from button.

<v-btn small flat @click.stop="insertTag('{{title}}', <model-name-here>)">+ Title</v-btn>

The method insertTag provide this:

this.$refs[model][0].focus()

I don't know how I can insert text to cursor position in textarea...

like image 347
pirmax Avatar asked Dec 21 '25 09:12

pirmax


2 Answers

Kallan DAUTRICHE's answer is on the right track, but not quite what I needed (or what the OP needed I think).

You have to set the ref of the element so you can directly select the input element of your DOM to get/set selection details

Template:

<v-text-field v-model="model" ref="textField">

Script:

export default Vue.extend({
    data: () => ({
        model: "",
    }),
    methods: {
        insertText(text) {

            // Get the input element by tag name, using the ref as a base for the search
            // This is more vue-friendly and plays nicer when you duplicate components
            const el = this.$refs.textField.querySelector("input");

            // Insert text into current position
            let cursorPos = el.selectionEnd; // Get current Position
            this.model =
                this.model.substring(0, cursorPos) +
                text +
                this.model.substring(cursorPos);

            // Get new cursor position
            cursorPos += text.length;

            // Wait until vue finishes rendering the new text and set the cursor position.
            this.$nextTick(() => el.setSelectionRange(cursorPos, cursorPos));

        }
    },
});
like image 181
sploders101 Avatar answered Dec 24 '25 04:12

sploders101


I had the same problem to insert emoji in the right place in a text field. I found a quick fix, but after inserting my emoji, the cursor moves to the end of the input field. Maybe if you insert text and not a native emoji, you will not have my problem.

You have to set the id of the element and not its reference so you can directly select the input element of your DOM and take the attribute "selectionEnd"

<template>
    ...
    <v-text-field v-model="model" id="inputTextField">
    ...
</template>

<script/method>
   ...
   let out = <yourVariableText>
   let cursorIndex = document.getElementById('inputTextField').selectionEnd;
   out = out.substring(0, cursorIndex) + tagToInsert + out.substring(cursorIndex);
   ...
</script/method>

This is an old post but I hope this answer can help someone

like image 39
Kallan DAUTRICHE Avatar answered Dec 24 '25 04:12

Kallan DAUTRICHE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!