How to Reset Text Fields with a Button Click in Vue.js?

I am currently working on a layout where I need to loop through text fields and buttons. How can I implement a function for each button that clears only the corresponding fields? Take a look at this fiddle here.

<div id="app">
  <h2>Each text field should have its own state and clicking the clear button should only clear that specific field</h2>
  <ul v-for="todo in todos">
    <li>
      <input type="text" :placeholder="`${todo.text}`">
    </li>
    <li>
      <input type="text" :placeholder="`${todo.text1}`">
    </li>
    <button>Clear</button>
  </ul>

new Vue({
  el: "#app",
  data: {
    todos: [
      { text: "Learn JavaScript", text1:"Hey" },
      { text: "Learn Vue", text1:"Hello"  },
      { text: "Play around in JSFiddle", text1:"Ciao"  },
      { text: "Build something awesome", text1:"Something"}
    ]
  }
})

Answer №1

If you need to reset specific fields, you can create a method called clear. Before implementing this method, make sure to include value and value1 properties for each item in the todo array and bind them to the respective fields as shown below:

new Vue({
  el: "#app",
  data: {
    todos: [{
        text: "Learn JavaScript",
        text1: "Hey",
        value1:'',
        value:''
          
      },
      {
        text: "Learn Vue",
        text1: "Hello",
        value1:'',
        value:''
      },
      {
        text: "Play around in JSFiddle",
        text1: "Ciao",
        value1:'',
        value:''
      },
      {
        text: "Build something awesome",
        text1: "Something",
        value1:'',
        value:''
      }
    ]
  },
  methods:{
       clear(i){
       this.todos[i].value='';
        this.todos[i].value1='';
       }
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
  <h2>Each text with it's own state and clear should reset the respective text fields</h2>
  <ul v-for="(todo,i) in todos">
    <li>
      <input type="text" :placeholder="`${todo.text}`" v-model="todo.value">
    </li>
    <li>
      <input type="text" :placeholder="`${todo.text1}`"  v-model="todo.value1">
    </li>
    <button @click="clear(i)">Clear</button>
  </ul>
</div>

Answer №2

It is highly recommended to review the documentation available at https://v2.vuejs.org/v2/

In order to achieve your goal, you need to include several basic constructors that are currently missing. First and foremost, add the click event to the button. (https://v2.vuejs.org/v2/guide/events.html)

Additionally, make sure to reference the index of the todos while rendering them (https://v2.vuejs.org/v2/guide/list.html)

Following these steps, create a straightforward method named clear:

new Vue({
  el: "#app",
  data: {
    todos: [
      { text: "Learn JavaScript", text1:"Hey" },
      { text: "Learn Vue", text1:"Hello"  },
      { text: "Play around in JSFiddle", text1:"Ciao"  },
      { text: "Build something awesome", text1:"Something"}
    ]
  },
  methods: {
    clear (index) {
      // Allows for unlimited keys
      for (let key in this.todos[index]) {
        this.$set(this.todos[index], key, null);
      }
    }
  }
})

Note that within the clear method, reactivity is ensured by utilizing the $set method (https://v2.vuejs.org/v2/api/#vm-set) and referencing the corresponding index.

Lastly, the inputs value is bound to the todo model using Vue's v-model. Do I earn extra credit for this? (https://v2.vuejs.org/v2/api/#v-model)

For the complete code sample, visit: https://jsfiddle.net/cdsgu62L/10/

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

Add a container element resembling a div inside a table without implementing the table layout

I am working with a table that is rendered by DataTable, and I have the requirement to dynamically append new elements inside the table like this: The dark grey area represents the new DOM elements that need to be inserted dynamically. The first row cont ...

An issue occurred while deploying Docker on Railway services: Build Error

After successfully deploying my Django project on Railway, I decided to add SendGrid mail functionality using the django-sendgrid-v5 package. Everything worked fine in the development environment, including sending emails like user signups. However, when ...

Unselect all checkboxes except for the one that was clicked

In a project, I have 3 checkboxes that are interconnected and when one is clicked or checked, I want the others to be cleared while keeping the clicked checkbox checked. This behavior is similar to radio buttons but I cannot use radio buttons due to client ...

Negatives of utilizing two different UI libraries within a single react project?

I have been contemplating a decision that may be considered unconventional from a technical standpoint. Despite my search efforts, I have not come across any explanation regarding the potential drawbacks of this decision. Imagine creating a React website ...

Contrast between categories and namespaces in TypeScript

Can you clarify the distinction between classes and namespaces in TypeScript? I understand that creating a class with static methods allows for accessing them without instantiating the class, which seems to align with the purpose of namespaces. I am aware ...

Modifying CSS style according to the contents of an HTML element

Creating a room allocation page with multiple panel boxes using Bootstrap. Each box represents a bed - highlighted in red if occupied and green if vacant. Clicking on a green panel redirects to the room allocation page, while clicking on a red panel goes t ...

Incorporating visual card images instead of textual descriptions by utilizing arrays in a card game

Every time I run my blackjack/21 game program, it crashes after the player chooses to stick. I have double-checked the console for errors, but none are showing up. Testing the JavaScript code separately in a REPL works perfectly fine, so I'm not sure ...

Editing the app.js file can cause it to malfunction and stop working

As I work on designing a webpage for a construction company using a template, I face an issue with the js file named app.js. Whenever I make edits to the script, the entire HTML page loses its responsiveness as if the js file was never included in the firs ...

Create a d.ts file for Vue components that are written using Typescript

As a newcomer to Vue, I am eager to dive into creating components and publishing packages to NPM. My plan is to develop Vue (typescript) + Vuetify reusable components that can be easily installed from NPM into any of my projects. While I have successfully ...

The style of MUI Cards is not displaying properly

I've imported the Card component from MUI, but it seems to lack any styling. import * as React from "react"; import Box from "@mui/material/Box"; import Card from "@mui/material/Card"; import CardActions from "@mui/m ...

Movement and physics mechanics for players using Physi.js

As I work on a basic game using Three.js for rendering and Physijis for physics, my question can be applied to games in general. In games, players often display movement that appears disconnected from the physics engine. They can accelerate instantly and ...

Exploring the world of Vue.js and Quarkus: creating, developing,

As a beginner, I have many questions, but one that is currently on my mind relates to a project I am working on. The company I am with is developing a program with the backend built in Quarkus (Java) and the frontend in Vue.js. My query is whether these tw ...

What is the process for incorporating the 'url-regex' npm package into an Angular(2/4) project?

I'm currently working on a project with Angular 4 and I've run into some issues while trying to use the url-regex package within my Component. After some troubleshooting, I discovered that this approach seems to work: import * as urlRegex from ...

What is the best way to choose a key from a discriminated union type?

I have a discriminated union with different types type MyDUnion = { type: "anonymous"; name: string } | { type: "google"; idToken: string }; I am trying to directly access the 'name' key from the discriminator union, like thi ...

`problem encountered when attempting to sanitize HTML through the npm package known as "sanitize-html"`

After researching the documentation, I attempted to use this code snippet: const dirty = '<div>Content</div>'; const clean = sanitizeHtml(dirty); The desired result of 'clean' should be "Content", however it seems that &apo ...

Several ways to display images with interactive captions

I am in need of multiple image modals with different descriptions. Each image should have a unique caption that appears when clicked. I have searched for solutions that display alt text for each image, but I require it to show other specific texts upon cli ...

Problem with Vue.js run serve after installation

Recently, I set up Vue on my terminal using the following command: sudo npm install -g @vue/cli Following that, I created a new project, navigated to the folder, and attempted to run the server with the commands: vue create frontend cd frontend npm run se ...

Ensuring the accuracy of a condition within an HTML form through the utilization of

I am interested in designing an HTML page that includes a small form. The form should include: Name Gender Date of Birth "I Agree" checkbox Submit button One important condition to note is that if the individual's age falls between 20 and 25 (calc ...

When working with AngularJS' ng-repeat in IE8, JQuery may encounter difficulties reading the innerHTML of a table row

I am attempting to implement a hover effect on table rows that changes the color when the mouse enters the row. I am utilizing JQuery and the on() method for this purpose, while the table is generated using AngularJS' ng-repeat. Everything works smoo ...

Set the present month as the default value for the input type month in a vue.js application

Is there a way to populate the current month in an input type month in vue.js? I'm not sure how to go about it. Any suggestions? HTML: <input type="month" v-model="month"> JS: data() { return{ date: ...