vue.js - Add a placeholder in text box with click of a button

Viewed 647

I have a textbox

<div>
   <b-form-textarea
   id="textarea"
   v-model="text"
   placeholder="Certification text "
   rows="5"
   max-rows="6"
   ></b-form-textarea>
</div>  

And two buttons

<b-button variant="primary" class="btn btn-primary btn-lg top-right-button mr-1">Save</b-button>
<b-button variant="info" class="btn btn-info btn-lg top-right-button mr-1">Add Name</b-button>

When the user is typing and in between if he clicks Add Name button {name} should be placed in the textbox (Where ever the cursor is). How can i implement it?

1 Answers

You can add a ref to your textarea, and access the selectionStart property, which contains the placement of the cursor. You can then use this index to splice the given text into the textarea's text at the given position.

And since clicking the button will lose the focus of the input, you can add it back by calling the focus method on the ref, along with setting the selectionStart and selectionEnd so the cursor is where it left off.

new Vue({
  el: "#app",
  data() {
    return {
      text: ""
    };
  },
  methods: {
    addName() {
      const { text } = this;
      const textarea = this.$refs["my-textarea"].$el;
      const index = textarea.selectionStart;
      const name = "{name}";

      this.text = `${text.substring(0, index)}${name}${text.substring(
        index
      )}`;
      textarea.focus();
      setTimeout(() => {
        textarea.selectionStart = index + name.length;
        textarea.selectionEnd = index + name.length;
      });
    }
  }
});
<script src="https://unpkg.com/vue@2.6.12/dist/vue.min.js"></script>
<script src="https://unpkg.com/bootstrap-vue@2.17.3/dist/bootstrap-vue.js"></script>

<link href="https://unpkg.com/bootstrap@4.5.2/dist/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://unpkg.com/bootstrap-vue@2.17.3/dist/bootstrap-vue.css" rel="stylesheet" />

<div id="app">
  <b-form-textarea ref="my-textarea" v-model="text" placeholder="Certification text" rows="5" max-rows="6">
  </b-form-textarea>
  <b-btn variant="primary" size="lg" @click="addName">
    Add Name
  </b-btn>
</div>

Related