Monday 8 March 2021

focus() not working after axios call in Vue JS

I have a form in Vue JS which is submitted via axios call and after axios I want to focus on a specific input element but it is not working properly.

Here is the input:

<input type="text" class="form-control mb-2" :id="'txtTazkira' + s.id" 
 @input="setTxtTazkira($event, s.id)" :value="s.tazkira" />  

The following function is called on form submit:

submitForm() {
  this.form.txtTazkira = this.txtTazkira
  this.form.selectedNotebook = this.selectedNotebook.id
  this.nextSlot = document.getElementById('txtTazkira' + (this.form.slotId + 1))

  axios
    .patch('/Notebook/api/slots/' + this.form.slotId, this.form)
    .then((response) => {
      this.tazkiraSaved = true
      this.fetchSlots()

      this.nextSlot.focus()
      console.log(this.nextSlot)
    })
    .catch((errors) => {
      alert('Unable to save Tazkira, There might be some issues.')
      this.tazkiraSaved = false
    })
},

As it can be seen that after axios call I have this.nextSlot.focus() which does not set focus to the input element. I also tried to execute the following but did not work:

this.$nextTick(() => {
    this.nextSlot.focus();
});  

I also tried the following where I added :ref="'txtTazkira' + s.id":

<input type="text" class="form-control mb-2" :id="'txtTazkira' + s.id" 
@input="setTxtTazkira($event, s.id)" :value="s.tazkira" :ref="'txtTazkira' + 
s.id">  

And then tried the following in the js but still not working:

var newSlot = 'txtTazkira' + (this.form.slotId + 1);

axios.post(.....)
{
  ...... 
  this.$nextTick(() => {
     this.$refs[newSlot].focus();
   });
}

I searched google and found some related discussions but that did not resolve my issue therefore I posted the question here.

Any help is appreciated in advance.



from focus() not working after axios call in Vue JS

No comments:

Post a Comment