geethika
geethika

Reputation: 369

vue js : How to set focus on disabled input field

<b-row v-if="detailsEditable">
                <b-col cols="6">
                  <b-form-group label="First name">
                    <b-form-input
                      ref="firstName"
                      v-model="userDetails.first_name"
                      :disabled="!detailsEditable"

                    ></b-form-input>
                  </b-form-group>
                </b-col>
                <b-col cols="6" class="pl-0">
                  <b-form-group label="Last name">
                    <b-form-input
                      v-model="userDetails.last_name"
                      :disabled="!detailsEditable"
                    ></b-form-input>
                  </b-form-group>
                </b-col>
              </b-row>
              <b-row v-else>
                <b-col cols="12">
                  <b-form-group label="Full name">
                    <div @click="enableField('name')">
                      <b-form-input
                        ref="name"
                        :value="
                          userDetails.first_name + ' ' + userDetails.last_name
                        "
                        :disabled="!detailsEditable"                            
                      ></b-form-input>
                    </div>
                  </b-form-group>
                </b-col>
              </b-row>
<script>
export default {
  data() {
detailsEditable: false,
}
}
</script>

When click on 'Full name' field, I need to set focus on 'First Name' input box, which is disabled and show only if detailsEditable =true

I set focus in the method enableField. But it not works using $refs.

enableField(value) {
    const vm = this           
    vm.detailsEditable = true
    vm.$refs.firstName.focus() 
}

Upvotes: 0

Views: 1485

Answers (1)

Nipun Jain
Nipun Jain

Reputation: 1014

Try this:

enableField (value) {
  const vm = this
  vm.detailsEditable = true
  vm.$nextTick(() => {
    vm.$refs.firstName.focus()
  })
}

I think issue is the timing of Vue’s rendering. Vue buffers changes and essentially renders asynchronously. For this reason, you will likely want to call focus in nextTick.

Upvotes: 3

Related Questions