Techniques for accessing the most recent input values within a loop

Here is the HTML code snippet:

<div v-for="item in my_items">
    <div>
      <input type="text" :value=item.name />
    </div>
    <div>
      <button @click="edit(item.id, item.name)">Edit</button>
    </div>
  </div>

This is the associated JavaScript code:

export default {
    data() {
        return {
            my_items: []
        }
    },
    methods: {
        async edit(id, name){
            console.log("edit", id);
            console.log("name", name);
        },
    },
    async mounted() {
        this.my_items = [
            {id: 1, name: 'name1'}  
            ,{id: 2, name: 'name2'} 
        ];
    }
}      

When the component is mounted, two rows will be displayed with names "name1" and "name2". Each row has an edit button attached to it. If you change the input field value and then click on the edit button, the console still displays the "old" name for the variable. How can you access the current value in the input field from the "edit()" function?

Answer №1

To handle form inputs in Vue.js, you can utilize the v-model directive or combine the @input event listener with the :value binding:

const app = Vue.createApp({
  data() {
    return {
      my_items: []
    };
  },
  mounted() {
    this.my_items = [{id: 1, name: 'name1'}, {id: 2, name: 'name2'} 
    ];
  },
  methods: {
    edit(item) {
      console.log("item", item);
    },
  }
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <div v-for="item in my_items" :key="item.id">
  <div>
    <input type="text" v-model="item.name" />
  </div>
  <div>
    <button @click="edit(item)">Edit</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

A guide on resolving the 'Unexpected identifier array in JSON Parse Error' encountered during an AJAX Request

I'm currently working on setting up a Contact Form Validation and I require the variable $msg from a php script called 'sendEmail.php'. The actual mailing system is functional, as the script successfully receives form inputs from index.php a ...

Modifying input values in AngularJS/HTML

I'm encountering an issue with the ng-repeat function in AngularJS within my HTML code. The problem is that when I change the input with the ID 'add-price' in one cartproduct, it simultaneously changes in all other cartproducts as well. For ...

Components for managing Create, Read, Update, and Delete operations

As I embark on my Angular 2 journey with TypeScript, I am exploring the most efficient way to structure my application. Consider a scenario where I need to perform CRUD operations on a product. Should I create a separate component for each operation, such ...

"Autodesk Viewer: Unlocking the Power of Programmatic Camera Y-Axis Reversal

I have been utilizing the markups core extension to retrieve and restore the viewer state, which has been successful, except for a problem with inversion (only in 3D). When a client interacts with the y-axis specifically, causing the model to flip to revea ...

Struggling with a component that won't load in JSX?

Having some difficulty with React not rendering data associated with a component's props: import React from 'react'; import {ItemListing} from './ItemListing.js'; export var SearchResults = React.createClass({ render: functi ...

What is the size limit for JSON requests in Node.js?

I am seeking information about the req object in nodeJS. Let's say I have a code that sends data in JSON format to my server using an AJAX POST method. Now, imagine a scenario where a user manipulates my client code to send an excessively large JSON f ...

Having trouble getting Vue UI to install correctly on my new project using Laravel Framework version 8.83.7

I am having trouble installing Vue in my Laravel project. Here are the steps I follow: Run composer require laravel/ui Install Vue using: php artisan ui vue Install Vue with authentication using: php artisan ui vue --auth Then run: npm install ...

What is the proper way to utilize the script type "text/x-template" in a multilanguage context?

I'm currently working with ASP NET and VueJS. In my ASP NET, I have a view component that looks like this: <script type="text/x-template" id="form-template"> @if (string.IsNullOrEmpty(Model.LastName)) { <in ...

Displaying a DIV after entering text into an <input> field using JavaScript

Attempting to create a JavaScript function that will show/hide a 'DIV' after entering some text into an input field. I have successfully written the function, but I am struggling to make it only work when the user enters a value greater than 8. ...

Show the JSON response from the controller on the view page

In my controller, I have a JsonResult action that returns a list of House objects. My goal is to retrieve this data onclick using ajax and display the JSON data within my view. While I can see the proper response and JSON result in Firebug, I'm not su ...

The image component is missing the necessary "src" attribute even though a valid src value has been provided as a prop

I'm encountering an issue in Next.JS where a component is not recognizing the image source passed through a prop. I am providing the path of an image named "logo.jpg" from the project's public folder. The image successfully displays when used as ...

Menu/navigation bar designed with floating lines and an array of color options

I'm currently working on implementing this specific menu into my Wordpress site. My main concern is figuring out how to customize the hover effect for each navigation item. Currently, the float line changes to red (background-color:#800; height:2px;) ...

Implement a callback function for unchecked checkboxes on change

Currently, I am working with a gridview that includes a checkbox field. My goal is to use jQuery to create a function that activates when an unchecked checkbox is checked. function clickAllSize() { alert("helloy"); } $(document).ready(function () { ...

The JavaScript function modifies the value stored in the local storage

I'm in the process of developing a website that requires updating the value of my local storage when certain JavaScript functions are executed. Currently, I have this code snippet: localStorage.setItem('colorvar', '#EBDBC2'); I&ap ...

Problem with AngularJS factory causing issues with promises

I have a factory in AngularJS set up like this: 'use strict'; angular.module('frontRplApp') .factory('paymentService', function ($rootScope, $http, config, tools) { var urlBase = config.baseUrl; var payme ...

Encountering a compilation error when implementing ActionReducerMap in combination with StoreModule.forFeature

In my Angular project, the structure is organized as follows: /(root or repo folder) |_ projects |_ mylib (main library to be exported from the repo) |_ sample-app (created for testing 'mylib' project in other projects) To manage appli ...

Sending a blob through AJAX to a different domain using CORS

Could someone please explain why my current request is being blocked by the SO policy restriction? Javascript Code: var blob = new Blob([req.response], {type: "application/octet-stream"}); req = new XMLHttpRequest(); req.open("POST", ws_path(other_contex ...

After making changes to Vue, jQuery's data is now obsolete

Currently, I am in the process of transitioning from Jquery to Vue.js 3. As a result of this migration, Vue updates the DOM while Jquery still contains outdated information. My question is: How can I make Jquery reflect the new data just like Vue and Jav ...

What is the most effective way to assign multiple functions to the onClick event of a button, based on a specific property,

I have a special button that generates a specific type of code when rendered: <button>{this.props.text}</button> This button is named ButtonCustom. In the render method of the main container, I am trying to achieve the following: function my ...

Arrange a JSON array by searching texts initially, followed by sorting the remaining results in alphabetical order

I am looking to sort a JSON array in JavaScript based on a search text. The sorting should prioritize items that match the search text at the beginning of their value, followed by alphabetical sorting for the remaining results. Even if the search text is f ...