How to target input focus in Vue.js when using v-if within a v-for loop

I'm currently working on an app that allows users to add strings to a list and edit them. When the user clicks on the "edit" button, the <h3> element transforms into an input field using v-if/v-show conditional rendering. I want to enhance this functionality so that when the input field appears, it automatically gets focused.

Below is the code snippet:

<div class="card" v-for="(item, index) in list" :key="index">
        <!-- not editing -->
        <div v-if="editing != index + 1">
          <button class="edit-btn" @click="setEditing(item, index)">
            edit
          </button>
          <h3 class="title">{{ index + 1 + ". " + item }}</h3>
          <button class="delete-btn" @click="deleteEntry(index)">
            bin
          </button>
        </div>

        <!-- editing -->
        <div v-show="editing == index + 1">
          <button
            class="edit-btn"
            style="background-color:white;color:grey;border-color:grey;font-weight:bold"
            @click="cancelEdit"
          >
            x
          </button>
          <input
            ref="editInput"
            autocomplete="off"
            @change="console.log(entry)"
            class="edit-input"
            id="edit-input"
            @keyup.enter="saveChanges(index)"
            v-model="entry"
          />
          <button
            class="delete-btn"
            style="background-color:white;border-color:green;color:green"
            @click="saveChanges(index)"
          >
            mark
          </button>
      </div>
    </div>

function

setEditing(entry, index) {
      this.editing = index + 1;
      this.entry = entry;
      var el = this.$refs.editInput[index];
      console.log(el);
      el.focus();
      // document.getElementById("edit-input").focus();
    },

variables

data() {
  return {
    editing: 0,
    newEntry: "",
    list: [],
    error: "",
    entry: "",
  };
},

Answer №1

When using v-show, it may cause a delay in updating the DOM which could result in incorrect functionality of input focus. To ensure correct behavior, it is recommended to place the <code>el.focus()
method inside the nextTick function.

The proper usage of nextTick as per Vue documentation is:

Delay the execution of a callback until after the next update cycle of the DOM. It should be used right after data has been changed to wait for the DOM to be updated.

setEditing(entry, index) {
      this.editing = index + 1;
      this.entry - entry;
      var el = this.$refs.editInput[index];
      console.log(el);
      this.$nextTick(() => {
          el.focus();
      })
},

Answer №2

Give this a shot:

Utilize the following code snippet to achieve the desired outcome: 
this.$nextTick(() => this.$refs.editInput[index].focus())

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Validation of forms in Angular using a pseudo submission method

On a webpage, there is a form with two buttons: one to calculate a price and the other to submit the form. Below is a basic example: <form novalidate name="formStep1"> <select ng-model="address" required> <option></option> ...

Can we determine if scrollIntoView is compatible with different browsers through testing?

I am searching for a method to conduct a real-time assessment of the scrollIntoView feature in my user's browser. This is not a simple "caniuse" check; instead, I want to implement graceful degradation. I am utilizing jQuery and would prefer to utiliz ...

Leveraging callback functions for dynamically updating a JSON structure

Recently, I've been working on a db_functions.js file that includes several functions designed to interact with a database. Here's an excerpt from the script: function getUsers(client, fn){ //var directors = {}; client.keys('*' ...

Guide to animating camera movement to the top using three.js

Is it possible to tween the camera to a top position with a focus on an object in three.js using tween.js? The camera tweens to the right spot perfectly. Please refer to this codepen: http://codepen.io/anon/pen/ObQxjV?editors=1111 Click here for image re ...

Issues with FF6 CSS Javascript MozBorderRadius functionality not functioning as expected

While attempting to set the border radius using JavaScript in Firefox 6, I'm experiencing some issues. Interestingly, when I use the same code with WebkitBorderRadius on Safari, it works perfectly. that.element.style.WebkitBorderRadius = '10px&a ...

Data is not appearing when using Node.js with mongoose and the populate() method

I am facing an issue while trying to display data from a database. Even though I have integrated 3 different schemas into one, the combined data is not being displayed as expected. I have attached all three schemas for reference. While async-await along w ...

Issue with onClientClick not functioning properly when performing a jQuery function call

How can I make a jQuery form appear when an ASP.NET server-side button is clicked by the user? Currently, when I click on the button during runtime, the page reloads quickly without displaying the jQuery form. I am aiming to achieve a similar effect show ...

Utilizing AngularJS to bind form fields with select boxes to enable synchronized data. Modifying the selection in the dropdown should dynamically

Currently, I am working on an input form that involves a select with various options. Depending on the user's selection, three additional fields need to be populated accordingly. For instance: If the user picks Option1, then the three other fields s ...

How do you populate a dropdownlistfor in ASP.NET MVC after a form

My issue is that <form> @Html.DropDownListFor(x => x.City, provinces, "--Select City--", new { @class = "dropdownList" }) @Html.DropDownListFor(x => x.district, Enumerable.Empty<SelectListItem>(), "--Select district--") < ...

What is the process for transforming a JSON object format to another in node.js?

I found myself with a json object structured as follows: { "sample1": { "4": 2245, "5": 2175, "6": 3495, "7": 1845, ... "11.5": 1674, "12.5" ...

Navigating through the map function within Protractor

In my Angular application, I have implemented a timeline that displays event dates with their respective descriptions. Below is the HTML source code for this feature: <!-- timeline --> <h4 class="font-thin m-t-lg m-b-lg text-primary-lt">Hi ...

Using VueJs to associate boolean values with dropdowns

I am currently working on a form with a dropdown menu containing two options: "True" and "False". My goal is to save the selected value as a boolean in the form. For instance, when the user selects "True", I want the value stored as true in boolean format ...

I'm having trouble importing sqlite3 and knex-js into my Electron React application

Whenever I try to import sqlite3 to test my database connection, I encounter an error. Upon inspecting the development tools, I came across the following error message: Uncaught ReferenceError: require is not defined at Object.path (external "path ...

How can I retrieve the height of a hidden image in Internet Explorer?

I am encountering an issue with images that have been set to display:none. I am using javascript (document.getElementById('elem').height) to retrieve the height/width of these images. While this method works in most browsers, IE is reporting th ...

How should errors be managed when dealing with REST GET arrays?

Within my application, I have a React front end that communicates with an Express server linked to a MongoDB database. The users within the system are grouped into different groups, with each group having its own dashboard. I am aiming to create a single w ...

Exploring JavaScript physics within a two-dimensional environment

I've been diving into learning Canvas (HTML5) on my own and I've managed to code most of a simple game engine. It's based on a 2D space theme with planets, stars, and celestial bodies. In my default "Sprite" class, there is a frame listener ...

Missing ng-required fields not displaying the has-error validation in AngularJS forms

While editing any part of their address, the user should see a red invalid border around each field to indicate that the full form is required. However, for some reason I can't seem to get the 'Address' field to display this border. The set ...

Issues with Subject.subscribe occurring beyond the constructor

If you're looking for a straightforward service, I've got just the thing for you. import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class XmlService { items$: Subject<Item[]> = ...

Presenting titles and buttons within a Bootstrap modal window

I have implemented a modal using vue-bootstrap. The code for the modal is as follows: <template id="child"> <b-modal v-model="showModal" size="lg"> <template v-slot:modal-header> <h4 class="modal-title"> ...

Error message: "Upon initial loading, Angular and Firebase are unable to map undefined"

After the initial load, it functions properly. However, I am seeking a way to implement a promise to prevent data mapping before it has fully loaded. Upon the first loading of the site, the error below is displayed. This issue may arise from attempting to ...