Using Vue.js to access input elements that are dynamically generated when a function is called

<div v-if="result.length" style="clear:both">
      <div v-bind:key="item.id" v-for="item in result">
        <div class="ui form">
          <div class="field">
            <label>Content</label>
            <textarea id="dynamic-textarea-{{item.id}}" cols="30" rows="10">{{item.content[0]}}</textarea>
          </div>
          <div class="field right aligned">
            <button @click="updateData($event, item.id)" class="ui primary button">Update</button>
          </div>
      </div>
</div>

During the iteration above, I am trying to find a way to access the value of the 'current' textarea when the updateData function is called. I considered assigning an id to the textarea input or using $ref, but it didn't quite work as expected. Any assistance on this issue would be greatly appreciated. Thank you!

Answer №1

Using an array of refs

Make sure to utilize the index from the loop

Access the refs using the corresponding index

<div v-bind:key="item.id" v-for="(item, index) in result">

<textarea ref="textarea" name id cols="30" rows="10">{{item.content[0]}}</textarea>

<button v-bind:id="item.id" @click="updateData($refs.textarea[index])" class="ui primary button">Update</button>

Answer №2

To implement databinding for textareas, simply pass the current item to your update function:

Vue.config.productionTip = false; // disable production tip

new Vue({
    el: "#app",
    data: {
        result: [
           {id:0,content:['some content']},
           {id:1,content:['some content']},
           {id:3,content:['some content']},
        ]
    },
    methods:{
        updateData(item){
            alert(item.content[0]);
        }
    }
    
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div v-bind:key="item.id" v-for="item in result">
    <div class="ui form">
      <div class="field">
        <label>Content</label>
        <textarea name id cols="30" rows="10" v-model="item.content[0]"></textarea>
      </div>
      <div class="field right aligned">
        <button v-bind:id="item.id" @click="updateData(item)" class="ui primary button">Update</button>
      </div>
  </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

Ways to retrieve a converted document using the Microsoft Graph API

I'm encountering an issue when trying to save a PDF file received from the Microsoft Graph API. The call I am making looks like this: const convertConfig = { headers: { Authorization: <my token> } }; convertConfig.headers['C ...

Tips for confirming a date format within an Angular application

Recently, I've been diving into the world of Angular Validations to ensure pattern matching and field requirements are met in my projects. Despite finding numerous resources online on how to implement this feature, I've encountered some challenge ...

What is the best way to delete an entire node from Firebase?

I am currently working with the following database structure: https://i.sstatic.net/efG2u.png This specific command ended up deleting my entire database. var firebaseRef = firebase.database().ref(); firebaseRef.child(`users/${uid}/todos`).remove().then( ...

Tips for creating a mock for a function that yields a JSX Element

I am facing a problem where I have a function that returns a JSX Element. Here is a snippet of the code: myFunction.jsx const myFunction = (props) => { // ... do something with props return <MyElement {...newProps} /> } // MyElement.j ...

When attempting to utilize the Vuex store in a child component, it appears to be ineffectual

I'm experiencing an issue with the vuex-Store. There is a state in my store that is not being updated when the Action is called. Can anyone help me out here? The problem lies with the "selectedHive" state. The axios call is functioning properly and ge ...

Exploring LZMA compression in conjunction with next.js

Is anyone familiar with using the lzma algorithm to compress video, photo, text, etc. in the Next.js framework? I have searched everywhere but couldn't find a solution. I haven't found a proper demonstration or answer anywhere. I would greatly a ...

Locating discord.js users who possess multiple roles

Here is my code in its entirety as I have received some confusion on other forums: I am working on creating a Discord bot that can list users with a specific role. The plan is to create an array of roles, compare user inputs to the array, and display user ...

How can we best understand the concept of custom directives using the link method?

As a beginner in AngularJS, I am looking to implement an autocomplete feature for text input. My JSON data is stored in JavaScript and I need help simplifying the process. Can you provide me with a straightforward solution? The specific requirement is to ...

Tips for expanding a script that relocates a logo into a navigation consisting of several unordered lists

I recently implemented a jQuery script to center a logo within my main navigation bar only when the screen width is above 980 pixels. It was working perfectly fine with a single unordered list, but as soon as I added more unordered lists within the nav, it ...

Renew the php blade foreach loop using jQuery to update data live

I have a foreach cycle in my HTML, and at one point, some data is posted from JavaScript. I would like to append it once it is added to the database. I need to find a way to refresh the foreach loop without reloading the entire page (I could simply use ap ...

Retrieve the array element that is larger than the specified number, along with its adjacent index

Consider the following object: const myObject = { 1: 10, 2: 20, 3: 30, 4: 40, 5: 50, }; Suppose we also have a number, let's say 25. Now, I want to iterate over the myObject using Object.entries(myObject), and obtain a specific result. For ...

Vue's reactivity fails to activate when utilizing Bootstrap 5's alert container

Why Vue's reactivity is not triggered when using Bootstrap 5's alert div? Take a look at my code: <template> <div> <div v-if="alertICDMsg!==''" id="alertICDCode" cl ...

Error occurred within node while attempting to create a directory using mkdirsync

I wrote some code. try{ var Storage = multer.diskStorage({ destination: function (req, file, callback) { fs.mkdirSync('/home/data/' + file.originalname, { recursive: true }, (error) => { ...

Design the parent element according to the child elements

I'm currently working on a timeline project and I am facing an issue with combining different border styles for specific event times. The main challenge is to have a solid border for most of the timeline events, except for a few instances that share a ...

How can I turn off autocomplete in MUI textfields?

Currently, I am working with the latest version of mui. Within my user contact info form, there is a zip code field that I do not want to be auto completed if the value is null. However, despite my efforts, it continues to autocomplete with the email saved ...

Center column with header and footer flanking each side

Trying to replicate the layout of the Facebook Android app on my page. The app features a 3 column design, with the central column exclusively displaying the header (no footer included, although I require one for my version). This visual representation is ...

The issue of receiving an undefined JSON response persists in an AJAX file upload scenario

Currently, I am utilizing Valum's Ajax File uploader for handling same-page file uploads. The issue I'm facing is that despite numerous attempts and variations in my script, I consistently receive "undefined" when trying to access responseJSON[&a ...

The success method in the observable is failing to trigger

Could someone explain why the () success method is not triggering? It seems to be working fine when using forkjoin(). Shouldn't the success method fire every time, similar to a final method in a try-catch block? Note: Inline comments should also be c ...

Initiate an Ajax call to pre-fetch video content

I've been attempting to download a video from my own source and display a loading message while it's being downloaded. Once the download is complete, I want to hide the loading icon and have the video ready for playback. My issue lies in gettin ...

Surprising results when a class is applied using jQuery

Exploring the differences between two fiddles (make sure to run the code on the jsfiddle pages to see the differences clearly). First Fiddle Simple demonstration: $("body").addClass("noScroll"); alert($("body").hasClass("noScroll")); $("body").removeCla ...