What is the process for retrieving values from dynamic textareas using Vue JS?

Within the v-for loop, I am creating dynamic text fields. My dilemma now is how to retrieve the values of these inputs, as they are not a fixed number input so that I can assign their variables in the data().

This is how I am rendering the inputs:

  <ion-list>
        <ion-item v-for="(worker, index) in this.workers" :key="index">
          <ion-label text-wrap>
            {{ worker.name }}
          </ion-label>
           <ion-textarea placeholder="Enter Detail..."></ion-textarea>
        </ion-item>
      </ion-list>

      <section style="margin: 20px 30px;--color: #272727;"></section>
      <section>
        <ion-button
          shape="round"
          expand="full"
          @click="submit"
          style="--background: #272727;text-transform: capitalize;font-size: 16px;color: #ffc946;"
        >Submit</ion-button>
        <!-- Save -->
      </section>

Within the submit() method, my goal is to retrieve values from all these textareas.

Answer №1

  1. Make sure not to use this in the template section. Vue should ideally provide a warning or even an error for this.
  2. Focus on the data set and structure when working with Vue. Rather than extracting data from an input field, generate an input field based on your existing data. This approach may seem like a paradoxical concept, but it can help you better understand Vue and other reactive frameworks.

Here is a simple example:

Vue.component("InputField", {
  props: ['id', 'value'],
  computed: {
    fieldValue: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit("update:value", val)
      }
    },
  },
  template: `
    <div>
    {{ id }}
    <input
      type="text"
      v-model="fieldValue"
    />
    </div>
  `
})
new Vue({
  el: "#app",
  data() {
    return {
      formFields: [],
    }
  },
  methods: {
    addField() {
      this.formFields.push({
        id: this.formFields.length + Date.now(),
        value: null,
      })
    },
  },
  template: `
    <div>
    <button
      @click="addField"
    >
      ADD FIELD +
    </button>
    {{ formFields }}
    <hr />
    <input-field
      v-for="field in formFields"
      :key="field.id"
      :id="field.id"
      :value.sync="field.value"
    />
    </div>
  `
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>

Answer №2

In this example, we are utilizing the v-model directive to capture input values and implementing a debounce function with a delay of 250 milliseconds when interacting with the button.

<ion-list>
        <ion-item v-for="(worker, index) in this.workers" :key="index">
          <ion-label text-wrap>
            {{ worker.name }}
          </ion-label>
           <ion-textarea placeholder="Enter Detail..." v-model="input"></ion-textarea>
        </ion-item>
      </ion-list>

      <section style="margin: 20px 30px;--color: #272727;"></section>
      <section>
        <ion-button
          shape="round"
          expand="full"
          @click="submit"
          style="--background: #272727;text-transform: capitalize;font-size: 16px;color: #ffc946;"
        >{{buttonText}}</ion-button>
        <!-- Save -->
      </section>

Script file/tag:

export default{
data:{
input: "",
buttonText: "Submit xyz"
},
watch: {
   input: _debounce(function(){
   this.buttonText = this.input !== "" ? "Submit" + this.input : "Submit";
  }, 250)
 },
}

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

Why is the Google Map missing from the Bootstrap modal dialog?

I have multiple links on my website, each describing a different location with unique map data. I would like to display a modal bootstrap dialog with an embedded Google map when a user clicks on any of the links - ensuring that the location shown correspon ...

Utilizing JavaScript to Retrieve Selected Parameter in SSRS Report

Currently, I am incorporating an SSRS report into my website using Iframe. I aim to share a link to the specific filtered report, which is why I require knowledge of the report's parameters. My query pertains to how I can identify these parameters (e ...

Is there a way to remotely access and read text files stored on a server using either JavaScript or Ajax from an IIS6.0 Virtual directory?

Is it possible to use JavaScript or Ajax to read the text from a file on a remote machine (from IIS6.0 Virtual directory) and then copy it into a specific folder on the client machine? ...

VueJS: The current date is before today's date when using Date.now

I am currently comparing two dates in order to perform a filtered search. My goal is to only include objects in the filtered results if the date is after today, excluding any objects dated for today. However, when I run my code, it appears that items wit ...

When manipulating an array in JavaScript, the final count is wrong and there is an unexpected object

When I click this button, the addToCart function is invoked which dispatches an action to the reducer to add an item to the cart. The goal is to store only one instance of a specific item and increment the amount if the same item is added again. case &apo ...

Save the click value for future use

My appointment form is divided into separate panels. At Step 1, if a user clicks on London (#Store1), I want to hide the Sunday and Monday options from the calendar in panel 5. Essentially, I need to save this click event so that when the user reaches th ...

Do devDependencies get installed when running `npm install -g my-package` command?

After browsing through this forum discussion, I found the answers a bit confusing and not directly addressing my concern. Therefore, I am posing a specific question: When using the command npm install -g my-package, are the dependencies listed under devDe ...

Adding a unique object to a different user class with cloud code on Parse.com

I need to incorporate the current user object ID array into a user's "followers" column in Parse, but because of security restrictions, I have to use cloud code. Unfortunately, I don't know much about JavaScript and could use some assistance. Her ...

Error TS2451 in GatsbyJS: "react_1" block-scoped variable cannot be redeclared

Trying to implement typescript with custom routes in gatsbyjs: require("source-map-support").install(); require("ts-node").register(); exports.createPages = require("./src/createPages"); tsconfig.json { "include": ["./src/**/*"], "compilerOptions": ...

Can the target for orbit controls be set by clicking the mouse?

In my attempt to configure the orbit controls target in three.js, I encounter a challenge. For instance, when using , the camera consistently revolves around the center of the model unless the camera is panned. The desired behavior from the orbit controls ...

When the Button is clicked, scroll the element to the top position

I want to include an "ADD COMMENT" button on my page. When clicked, a form will be displayed for users to add comments. I would like the form to automatically scroll to the top position of the page so that users do not have to manually scroll down to vie ...

Transmitting HTTP headers using Node.js

Within my Node JS Express application, I have an API endpoint called 'download' that returns a buffer to the calling application along with a header named 'status', which is a Javascript object. The response from Node sends the buffer ...

Is Node.js compatible with Mysql Schema?

Currently working on a web service using Node.js, I've decided to switch from MongoDB to MySQL. With MongoDB, I could easily create a schema using Mongoose: var mongoose = require('mongoose'); var Schema = mongoose.Schema; mongoose.connect ...

Is it possible for the HTML data attribute to store a direct link to a specific DOM element?

Can the HTML data- attributes be used to store a reference to another DOM element? As shown in this jQuery example: var domel1 = document.getElementById("#mydiv"); var domel2 = document.getElementById("#mydiv2"); $(domEl1).attr('data-domel', dom ...

The folder serves as a module, however, the index.js file within the folder only consists of a few require

Currently, I am delving into the source code of hexo, a project built on top of node.js. Specifically, I came across a file named init.js: if (results.config){ require('./plugins/tag'); require('./plugins/deployer'); require('./pl ...

Continuously encountering the 403 error message "CSRF token missing or incorrect" within a Django and Vue configuration

After extensively searching through similar inquiries, I have yet to find a solution that works or sheds light on the issue at hand. My current setup consists of a Vue frontend (with its own routing) and a Django backend with an API. While all GET routes ...

Greetings! Unable to retrieve data within the TRY block following the resolution of an error in another function

Consider the following code snippet: const axios = require('axios'); const cheerio = require('cheerio'); let data = null; const parseNewCorporations = async (iter) => { let link2 = 'https://www.finanzen.net/aktien/' + ...

Encountering an issue after modifying the URL parameter in the Mongodb Driver within Express

Let's talk about the Product model: class Product { constructor(title, price, description, imageUrl) { this.title = title; this.price = price; this.description = description; this.imageUrl = imageUrl; } ...

VueJS: What is the easiest way to create a new instance of a div with just a click of a button?

Is there a way to create a function that will generate a new instance of a specific div (.container in the template) when a button (#addDiv) is clicked, with the button being the only visible element on the webpage initially? I have heard about using docum ...

Retrieving information from deeply nested JSON structures within React components

I am developing a web application that focuses on searching and displaying movie information. One of my challenges is accessing nested objects like "principals" from the same endpoint that contains the main object "title". Upon fetching the JSON response: ...