0

I've set up a Vue JS method which should automatically focus on the next input field if the maxlength of a field is reached. I'm trying to pass the field to focus onto through the function but it doesn't seem to work

I've tried using various setups, it seems to work if I pass the actual ref of the field, but not through the function

Method:

/**
         * Switch fields
         */
        switchToField(fieldSwitchName, fieldValue, fieldLength) {
          if (String(this.fieldValue).length >= fieldLength) {
            this.$refs.fieldSwitchName.focus();
          }
        }

HTML:

<div class="form-row">
                    <div class="form-group col">
                      <input v-on:keyup="switchToField(AppDOBMonth, formData.AppDOBDay, 2)" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" v-model="formData.AppDOBDay" name="data[ApplicationPayday][AppDOBDay]" id="AppDOBDay" v-validate="'required|numeric|max:2|min:2|max_value:31'" type="number" maxlength="2" pattern="[0-9]*" inputmode="numeric" class="form-control" placeholder="DD" @change="formData.AppDOBDay = leadingZeros(formData.AppDOBDay)">
                    </div>
                    <span class="dob-divider text-muted">/</span>
                    <div class="form-group col">
                      <input ref="AppDOBMonth" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" v-model="formData.AppDOBMonth" name="data[ApplicationPayday][AppDOBMonth]" id="AppDOBMonth" v-validate="'required|numeric|max:2|min:2|max_value:12'" type="number" maxlength="2" pattern="[0-9]*" inputmode="numeric" class="form-control" placeholder="MM" @change="formData.AppDOBMonth = leadingZeros(formData.AppDOBMonth)">
                    </div>
                  </div>

My code should be passing the value of fieldSwitchName into this.$refs.fieldSwitchName.focus();, but it seems to be looking for a fieldSwitchName ref rather than the value being passed in.

What am I missing here?

Ryan H
  • 2,620
  • 4
  • 37
  • 109
  • see https://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets – Cody G May 08 '19 at 11:25

2 Answers2

0

Using the . notation you're directly pointing to the name you've supplied after the . operator on a JS object.

To dynamically assign the accessing object key, you'll need an approach like this:

this.$refs[fieldSwitchName].focus()

Rahul Chowdhury
  • 1,110
  • 12
  • 23
0

If switchToField is a variable, you need call $ref as array:

switchToField(fieldSwitchName, fieldValue, fieldLength) {
    if (String(this.fieldValue).length >= fieldLength) {
        this.$refs[fieldSwitchName].focus();
    }
}
Eric RF
  • 34
  • 4