Automatically focus input box within toggled text or input fields

I'm creating a dynamic form that switches <p> tags to <input> tags when clicked.

You can view an example of this functionality in action on JSFiddle: https://jsfiddle.net/50wL7mdz/314578/

The key part of the code is shown below:

<div id="app">
  <div v-for="msg in messages" :key="msg.txt">
    <div :class="{editing: msg.edit}">
      <p v-on:click="msg.edit = !msg.edit">{{msg.txt}}</p>
      <input type="text" v-model="msg.txt">
    </div>
  </div>
</div>

To improve user experience, I want the newly revealed <input> boxes to automatically be focused so users can start typing right away.

The challenge I face is handling multiple input fields generated dynamically (as seen in the JSFiddle).

Is there a way to set focus to new <input> boxes as they appear?

Answer №1

Check out this link for more details

<div v-for="(message, idx) in posts" :key="message.content">
    <div :class="{editMode: message.editing}">
      <p v-on:click="toggleEditMode(idx, $event)">{{message.content}}</p>
      <input type="text" v-model="message.content">
    </div>
  </div>

toggleEditMode(idx, event) {
      this.posts[idx].editing = !this.posts[idx].editing
            this.$nextTick(function(){
        event.target.parentNode.querySelector('input').focus()
      });
    }

Give this method a try - By passing the $event parameter to your click function in Vue, you can access the clicked element and manipulate it accordingly after the component has re-rendered. This allows you to focus on an input field after toggling a certain property.

Hope this helps!

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

Encountered an Uncaught ChunkLoadError with Vercel Next.js: Chunk 0 failed to load

Upon removing the node modules and package-lock.json files, I encountered the error mentioned above when attempting to reload any page. The project works fine after being restarted for the first time. However, upon reloading the page again, it displays a b ...

Could you please provide the NodeJS ES6 alternative syntax for importing the PouchDB library using the `let` keyword?

Currently, I am following a tutorial at https://medium.com/beginners-guide-to-mobile-web-development/getting-started-with-pouchdb-f0f3d7baebab on incorporating PouchDB into a server-side NodeJS script. However, I have encountered an issue in Step 1: cons ...

Heroku is experiencing issues with loading Firebase credentials

Difficulty with Firebase Integration on Heroku Currently, I am facing an issue with my Node.js server deployed on Heroku that interacts with Firebase. When attempting to run the application on Heroku, I encounter an error stating that it is unable to load ...

"Real-time image upload progress bar feature using JavaScript, eliminating the need for

I have successfully implemented a JavaScript function that displays picture previews and uploads them automatically on the onchange event. Now, I am looking to add a progress bar to show the upload status. However, all the solutions I found online are rel ...

Execute a function within a main module from a sub-module in Node.js

If I have a file named parent.js with the given source code: var child = require('./child') var parent = { f: function() { console.log('This is f() in parent.'); } }; module.exports = parent; child.target(); and ano ...

Selecting the default value in an AngularJS dropdown using ng-options

Question 1: Is there a way to set a default value using ng-option when the data is not in an array format? It seems simple when working with arrays, as I can easily do: select = $scope.items[0]; You can see a Demo here. Question 2: <select ng-model ...

The issue with angular JavaScript in the child component is causing the left side navigation dropdown to malfunction

I'm currently facing an issue with the left side navigation in my home component. The dropdown functionality is not working within one of the routing modules (admin-routing.module.ts). Interestingly, the navigation works perfectly fine in app-routing. ...

Remove the class from all child elements and apply the class to the parent or ancestor of the element that was clicked on using

The Goal: I aim to achieve the following outcome. Whenever a user clicks on any of the radio inputs within the div that has the class corp-struct, I want to assign the following class to the parent element two levels up. This means that, in the example bel ...

Converting JavaScript Arrays into Strings Automatically

Just started learning JS, so there's still a lot to discover While browsing, I stumbled upon this interesting information (See Image) on https://www.w3schools.com/js/js_array_methods.asp According to them, "JavaScript automatically converts an array ...

Efficiently generating and managing numerous toggle buttons in Reactjs with Material-ui ToggleButtons

Currently, I am exploring the idea of designing a sidebar that incorporates a variable number of toggle buttons generated from an object containing keys and values. However, I am encountering difficulties in utilizing the "key" value to adjust the corres ...

Stop the change event from occurring on a textarea when the user clicks on an external cancel button

In a particular scenario, there is a textarea with an autosave feature triggered by the change event. When the textarea is focused on, Save and Cancel buttons appear at the bottom, providing users with options in case they prefer not to simply click outsid ...

After successfully installing create-react-app, it encounters an issue when trying to execute the "start" command

Using NodeJS portable version 12.4.0 on Windows 10 (due to restrictions on installing NodeJS on my corporate computer). Executing npx create-react-app myApp completes without any errors. It's worth noting that I have another app created some months b ...

Animate the removal of a div message with the help of CSS and jQuery

To display a success message in PHP, I use the following code snippet: <div class='alert alert-success'>Success!!</div> In addition to that, I have implemented a CSS3 animation called Animate: .animated { -webkit-animation-durati ...

Simple method to retrieve unordered list identifiers as an array using PHP

Currently, I am working with an unordered list where I am using DB ids as the list-item ids. When the Submit button is pressed, I want to present all the ID's of my list items as an Array in PHP. I am still learning JavaScript and although there are s ...

Establishing the bottom limit for the vertical axis on a column chart with the Visualization Google API

I am currently working on implementing the Google Chart API alongside AngularJS. I attempted to adjust the min property of the vertical axis for my column chart to 0 using the following code: var dataMois = CaDuMois.query(function(){ $scope.comparat ...

Different approach to handling response interceptors in AngularJS framework

Is there an alternative to $httpProvider.responseInterceptors since it has been discontinued in AngularJS V1.3? The interceptors that were functioning with Angular JS 1.2 are no longer operational in version 1.3 var angularErrorHandling = angular.module( ...

The image fails to display when using THREE.js and Panolens.js

Trying to create a 360-degree environment with informational buttons using THREE.js and Panolens.JS However, I'm unable to resolve why the image is not appearing. Continuously encountering the error: Uncaught ReferenceError: process is not defined. ...

Replacing an Angular 2 application with a new webpage

I've been working on a project using Angular 2 and following this tutorial: Every time I run my api with npm run api on localhost:3000, the entire application gets replaced by another webpage. https://i.sstatic.net/5pIfX.png Here is my package.json ...

Prevent duplicate words from being entered into an input field using jQuery or JavaScript to trigger an alert

Here is the information I need: <input type='text' class='myprofiletags' name='my_profile_tags' value='' /> To ensure that users do not enter the same word multiple times, I am looking to create an alert when ...

After Vue 3 <router-view> was built in history mode, it received comments

My Vue project works perfectly in hash router mode, but when I switch to history mode, only the navbar is displayed and the <router-view> is commented out. I have already configured my apache settings for history mode. router.js import { createRoute ...