Pheonix
Pheonix

Reputation: 177

Keeping the cursor on the textbox after pressing Enter button

I wanted a small help in VUEJS. I have a form and i have a text box. When clicking the enter button its gives me some result and clears the text box but the blinking cursor doesn't come back to the text box. Any idea on how to achieve it ->

1. I write some text in the text box
2. Presses Enter 
3. Provides some info and clears the text box
4. Same text box starts to blink and i need to be able to write something back again

Here is my code:

<template>
  <div class="app-container app-card">
    <div class="app-content">
          <b-form-input-with-validation
            v-model="number"
            :rules="{max: 255, required: true}"
            label="number"
            name="number"
            type="text"
            @keyup.enter="onSubmitClick"
            ref="track"
          />
    </div>
  </div>
</template>
<script>
  export default {

    methods: {
     
      reset() {
        this.innerValue.tracking_number = null
      },

      async onSubmitClick() {
        this.$refs.track.focus()
      },
    },
    data() {
      return {
        track: null,
      }
    },
  }
</script>

I am getting this error:

this.$refs.track.focus is not a function

Upvotes: 2

Views: 744

Answers (1)

Dan
Dan

Reputation: 63059

Place a template ref on the textbox so you can focus it from the clear method.

Options API (with <b-form-input>)

<b-form-input v-model="number" ref="refText"></b-form-input>
methods: {
 clear() {
    this.$refs.refText.focus();
  }
}

Composition API (with regular <input>)

<input ref="refText" />
setup() {
  const refText = ref(null);
}
const clear = function() {
   refText.value.focus();
}

Here is a demo:

const { createApp, ref } = Vue;
const app = createApp({
  setup() {
    const mytext = ref('press button to clear me');
    const refText = ref(null);
    
    const clear = function() {
      mytext.value = '';
      refText.value.focus();
    }

    return {
      mytext,
      refText,
      clear
    }
  }
});
app.mount("#app");
<div id="app">
  <input v-model="mytext" ref="refText" />
  <button @click="clear">Clear</button>
</div>

<script src="https://unpkg.com/vue@next"></script>

Upvotes: 1

Related Questions