The function to focus on this.$refs[("p" + index)] element is not available

I need help transforming a div into an input box when clicked, allowing me to edit the post inside a loop.

Here is the button found on the post:

<a @click="setFocusEdit(index)" v-if="isAuthor(post)" href="#" >Edit Me</a>

And here is the specific div in question:

<div :ref="'p' + index"  class="post-description">
    {{post.description}}
</div>

This is the method I am using:

  setFocusEdit(index) {
    console.log('focusing on', index);

    this.$refs['p' + index].focus();
  },

However, I am encountering the following error message:

Uncaught TypeError: this.$refs[("p" + index)].focus is not a function

Could you provide guidance on resolving this issue?

Answer №1

When utilizing the v-for directive, it is recommended to use the ref attribute with a static name such as posts, which will give you an array of the referenced elements.

new Vue({
  el: '#app',
  data: function() {
    return {
      posts: [{
          title: "post 1",
          content: "content 1"
        },
        {
          title: "post 2",
          content: "content 2"
        }
      ],

    }
  },

  methods: {
    setFocusEdit(index) {


      this.$refs.posts[index].focus();
    }

  },
  mounted() {

  }

})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>




<div id="app">
  <div class='col-md-4 mt-3' v-for="(post, index) in posts" :key="index">
    <textarea readonly ref="posts" class="post-description">
      {{post.content}}
    </textarea>
    <a @click.prevent="setFocusEdit(index)" href="#">Edit Me</a>
  </div>
</div>

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

Passing a list variable to JavaScript from Django: A step-by-step guide

Currently, I am facing an issue while attempting to generate a chart using Chartjs and Django. The problem arises when transferring data from views.py to the JavaScript code. Here is a snippet of my code in views.py: def home(request): labels = [&quo ...

Tips for Passing Parameters to Vuex mapActions correctly:Executing mapActions in Vuex requires a specific

I am facing an issue with my ProjectPage.vue where I display project issues in a v-data-table. The projects are fetched from a server API call in the sidebar and displayed there. Once I select a project, I want to use its id to retrieve its corresponding i ...

Using Javascript within HTML: A guide on when to utilize semi-colons and when to implement the return false statement

Exploring the use of JavaScript attributes within HTML elements: <input type="button" onclick="somceFunc()" /> <input type="button" onclick="somceFunc();" /> <input type="button" onclick="somceFunc(); return false;" /> Debating whether ...

Button from Material-UI vanishes upon being clicked

I encountered an issue with a button that disappears when clicked on. Additionally, clicking the button once does not trigger any actions associated with it. In order to execute the button actions, I have to click the area where the button was located afte ...

Can you explain how to extract information from an API response using res.send?

Utilizing the MEAN stack in JavaScript for my single page application has been seamless. A crucial component of my architecture involves an Angular factory that communicates with my API. app.factory('authorizing', function($resource){ retur ...

Determining the size of an image prior to uploading it in a React

The solution for this issue can be found using vanilla JavaScript here To clarify, instead of using alert(), my goal is to store the dimensions in the state object. How can I adapt this code into a React component utilizing the OnChange() event handler? ...

In Internet Explorer 11, the Content-Type setting is not functional and may cause issues with certain functionalities

My initial attempt to solve the issue involved using the method beginQuoteFileUnquoteUpload1, which created a proper boundary and Content-Type. However, upon receiving the file, I discovered that it was corrupted :( var formData = new FormData(); formD ...

How to retrieve data attribute from a different attribute in VueJS

I'm working with code that utilizes the VueGoodTable component, and I'm looking for a way to allow users to dynamically change the unit of the amount displayed: <template> <div class="container"> <h1>Welcome to t ...

Explore the Benefits of Using MUI V5 Grid Component for Your Box Design

Exploring MUI to delve into the world of React for the first time. Curious about the usage of the Box component alongside the Grid component. The example on the docs showcases this scenario. export default function BasicGrid() { return ( <Box sx={ ...

Unusual HTML Structure (content misplaced or out of order?)

Recently, I started learning CSS/HTML in school and we just delved into Javascript. Currently, we are working on a website project. However, while trying to integrate the content with the navbar, I encountered a strange issue. When resizing to 620px or le ...

Unlocking secure content with Ajax

Trying to access a webservice or webpage solely through ajax, as it is the only allowed method for some reason. The webservice is secured with corporate SSO. When requesting webpage X for the first time, you are redirected to login page Y, outside of the a ...

Issue: Attempting to render objects as React children is invalid. Consider using an array if you want to render a collection of children. This problem often occurs when fetching data from a JSON

Hey everyone, I'm currently working on a small website using ReactJS. After adding the code below, an error keeps popping up: Objects are not valid as a React child. If you meant to render a collection of children, use an array instead. Here's t ...

Searching for a column fails to yield any results after altering the value in

Here is a snippet of code that I am working with: <!DOCTYPE HTML> <html lang="en"> <head> <title> Exact matches overview </title> <script type="text/javascript" src="/static/s ...

The dark theme in React Material UI will be specifically targeted and applied only to the drawer

I want to implement a dark theme specifically for the drawer component. In Drawer.js <ThemeProvider theme={theme}> <div> {props.token && ( <Drawer anchor="left" open={props.isDrawerOpen} ...

How to transfer the application version from package.json to a different non-JSON file in Angular and node.js

While developing my Angular application, I encountered a task where I needed to extract the version number from the package.json file and transfer it to a non-json file. The content of my package.json file is as follows: { "name": "my app ...

What is the best way to gather Data URI content through dropzone.js?

I am currently utilizing Dropzone for its thumbnail generation feature and user interface. However, I am only interested in using the thumbnail generation ability and UI and would prefer to collect all the data URIs myself and send them to the server via a ...

Extracting timestamped text data from a simulated chat interface

I am looking to gather chat data from Twitch clips. These are saved moments from livestreams where viewer reactions are captured. Take a look at this example clip: While I can scrape all the data by watching the video and utilizing query selectors, my goa ...

Why do certain servers encounter the "Uncaught SyntaxError: Unexpected token ILLEGAL" error when loading external resources like Google Analytics or fonts from fonts.com?

Working on a variety of servers, I encountered a common issue where some externally loaded resources would throw an error in Chrome: "Uncaught SyntaxError: Unexpected token ILLEGAL". While jQuery from the googleapis CDN loads without any problems, attempt ...

Unable to locate the JavaScript files within the NextJs and ReactJs project

I've encountered an issue when trying to import js files (which are libraries) in my project. I am currently using NextJS version 14.1.3 and ReactJS version 18.2.0. You can find the path to these files here Here is a glimpse of the project structure ...

Have you ever wondered why MEAN.js applications use the #! symbol at the start of their URLs

Embarking on my first MEAN application build using MEAN.JS, I was intrigued by the structure of how mean.js organizes the application, particularly why URLs begin with /#!/. For instance, for the login page, I envisioned: http://example.com/login instea ...