Problem setting the focus on the correct element


#1

Hi,

this is a very simplified example of the form I am working on. When the form pops up, I give the first Element (Volvo) the focus with

this.$refs.firstOne.$el.focus()

so the user can select an option with the keyboard. All elements have a tabindex, from “1” to “6”. On the last button (Close) I listen to @keydown, in case of “Tab” the focus should move again to the first element, also with

this.$refs.firstOne.$el.focus() .

The problem: the focus moves always to the second element (BMW), not to the first one, even if more selects are following. Of course the second element has a different ref, both elements have different IDs too, I also tried with

document.getElementById("id_firstOne").focus()

but with the same result.

Any ideas?

Thanks

23

This is my code, reduced on what is necessary:

<template>
   <div>
      <div>
         <select id="id_ak" ref='ak' tabindex="1"> 
            <option value="volvo">Volvo</option>
         </select>
      </div>
       <div>   
         <select id="id_bk" ref='bk' tabindex="2"> 
            <option value="volvo">BMW</option>
         </select>
      </div>
      <div >
         <input  type="Number"  tabindex="3" /> 
       </div>
      <div >
         <input  type="text" tabindex="4" /> 
      </div>
      <div class="flex justify-end">
         <button tabindex="5" >Close</button>
         <button tabindex="6" @keydown="keyDn" >Save</button>
      </div>
   </div>
</template>

<script type='text/javascript'>
   export default {
      data () {
         return {
            elAkonto:undefined
         }
      },
      methods: {
         keyDn(e){
            if (e.key==='Tab'){
               this.setFocusAKonto()
            }
         },
         setFocusAKonto(){
            // this.elAkonto.focus()
            this.$refs.ak.focus()  // moves focus on second element (BMW)
         }
      },
      mounted(){
         //   this.elAkonto=document.getElementById("id_ak")
         // this.elAkonto.focus()
         this.$refs.ak.focus()  // moves focus correctly on the first element (Volvo)
      },
     
   }
</script>

Setting the focus in mounted() works (via $ref and getElementById) , but calling setFocusAKonto() after pressing Tab moves the focus always on the second element (BMW)


#2

Sorry for posting the above, it’s really no Vue-related problem I found out.

Adding an empty

<div id="test" tabindex="1"></div>

at the beginning and renumbering the tabindex of the following elements accordingly does the trick. Now the focus is moved from the last button when pressing Tab with

document.getElementById("test").focus()

to the first select (Volvo) as desired.

I really don’t understand this logic but: it works …