Deleting an item from a Vue.js list

I'm currently working on a project to develop a basic webpage that allows users to add or remove textboxes using vue.js.

new Vue({
  el: "#app",
 data() {
    return {
      list: []
    };
  },
  methods: {
    deleteFromList(index) {
      this.list.splice(index, 1);
    },
    addItem() {
      this.list.push({});
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<!DOCTYPE html>
<html>
  <head>
    <title>App</title>
    <meta charset="UTF-8" />
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  </head>
<body>
    <div id="app">
         <button @click="addItem()">Add 1</button>
      <ul>
          <li v-for="(item, index) in list":key="index">
            <textarea rows="1" cols="30">{{item}}</textarea>
            <button @click="deleteFromList(index)">Delete</button>
          </li>
      </ul>
    </div>

    <script src="index.js"></script>
  </body>
</html>

I've embedded the code snippet into the page (you may need to expand it for better visibility), but I've encountered an issue where clicking the Delete button removes the last row instead of the corresponding one. Can anyone provide guidance on resolving this error?

Many thanks for your assistance :)

Answer №1

Removing the correct item from the array is actually happening, but the change may not be visible because you are only updating the textarea value and not the model itself. The textarea is not directly linked to the value; it is just cached using :key="index". Here is an example that demonstrates this - by adding a counter, you can observe that the correct object is being deleted.

Vue.config.productionTip = false;
Vue.config.devtools = false;
new Vue({
  el: "#app",
  data() {
    return {
      list: [],
      counter: 0,
    };
  },
  methods: {
    deleteFromList(index) {
      this.list.splice(index, 1);
    },
    addItem() {
      this.list.push(this.counter++);
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

<div id="app">
  <button @click="addItem()">Add 1</button>
  <ul>
    <li v-for="(item, index) in list" :key="index">
      <textarea rows="1" cols="30">{{item}}</textarea>
      <button @click="deleteFromList(index)">Delete</button>
    </li>
  </ul>

  <pre>{{ list }}</pre>
</div>

To ensure dynamic changing values/models, utilize v-model for the value and use indexOf when removing items.

Vue.config.productionTip = false;
Vue.config.devtools = false;
new Vue({
  el: "#app",
  data() {
    return {
      list: []
    };
  },
  methods: {
    deleteFromList(item) {
      this.list.splice(this.list.indexOf(item), 1);
    },
    addItem() {
      this.list.push('');
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

<div id="app">
  <button @click="addItem()">Add 1</button>
  <ul>
    <li v-for="(item, index) in list" :key="index">
      <textarea rows="1" cols="30" v-model="list[index]"></textarea>
      <button @click="deleteFromList(item)">Delete</button>
    </li>
  </ul>
</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

The conversion of string to number is not getting displayed correctly when using console.log or document.write. Additionally, the concatenated display is also not functioning as intended

Being new to JS and HTML, this program was created to enhance my understanding of the concepts. I attempted a basic program to convert a string to a number in three different ways, but I am having trouble determining if the conversion actually took place. ...

npm package construction failed

https://i.stack.imgur.com/bk9r2.png Whenever I attempt to execute the command npm run watch, I consistently encounter this error message. Can someone please assist me with resolving this issue? Click on the image to view the problem. Thank you in advance. ...

Display or Conceal Multiple Divisions Using Angular 2

I am looking to implement a functionality using Li lists to toggle the visibility of multiple divs in Angular 2. Initially, all divs on the page will be visible. When viewing on a smaller screen, I want to hide some divs and show a specific div when a cor ...

Hover over or click to automatically focus on the input field

I have an icon that triggers focus on an input field when hovered over. I also want the same functionality to occur when the user clicks on the icon. if(!mobile){ $('#search-icon').hover( function(){ if($('.sear ...

Steps to indicate a selected check column in a grid

I am working with a grid that has a check column, and I need to programmatically mark the checkbox. This is how the check column is coded: columns: { items:[ { itemId: 'checkColumn', xtype: 'selectallche ...

Leveraging Affix in Bootstrap version 2.3.2

Hey there, I'm currently working on building a sidebar similar to the one you can find here. The issue I'm facing is that my sidebar overlaps with the footer at the bottom of the page. What I need is for the sidebar to move up when the user scrol ...

Modifying the Inactive Tab Color in Material UI

For my application, I have a specific requirement where the active tab needs to be styled in red and the inactive tab in blue. Here is how the styling is set up: newStyle: { backgroundColor: 'red', '&$selected': { b ...

Tips for restricting the size of uploaded files or the quantity of files in multer express and effectively managing any errors

I am currently working on a code that requires me to set limits on file size or the number of files that can be uploaded. For instance, I want to restrict users from uploading more than 100 files at once or limit the total upload size to 100 mb. However, ...

What is the best way to decrease the border width of a chartjs doughnut chart?

I have a vision for my chart based on the mockup: However, here is what I've been able to achieve using chartjs so far: This is the code I'm working with: datasets: [ { data: [3, 8, 13, 9, 2], backgroun ...

Change the URL structure from ex.com/forum?id=1 to ex.com/#/forum?id=1 in AngularJS

Hey there! I'm in the process of creating a Forum using AngularJS and need some guidance. First things first! I've successfully established a connection to my database with: <?php session_start(); $db = new mysqli("localhost","root",""," ...

I encountered an unexpected token error while using JavaScript syntax with objects

In my current coding project, I have encountered an issue while attempting to utilize an object from a different JavaScript file. Despite importing the necessary function from this external file, there seems to be a syntax error present. Can anyone offer ...

Retrieving data from a nested object with varying key names through ng-repeat

My JSON object contains various properties with unique names: var definitions = { foo: { bar: {abc: '123'}, baz: 'def' }, qux: { broom: 'mop', earth: { tree: 'leaf', water: 'fi ...

How can I set the background of specific text selected from a textarea to a div element?

Is it possible to apply a background color to specific selected text from a Text area and display it within a div? let elem = document.getElementById("askQuestionDescription"); let start = elem.value.substring(0, elem.selectionStart); let selection = ...

Surprise mistake: Jade's error with the length

What can I do to address this problem? The jade file in question is as follows: extends layout block content h1. User List ul each user, i in userlist li a(href="mailto:#{user.email}")= user.username U ...

Is it possible to use the same identifier for both the name and id attributes in HTML?

In the world of coding, the "name" attribute is often used in server-side programming to send name/value pairs in requests. On the other hand, the "id" attribute is commonly utilized in client-side programming such as Javascript and CSS. However, both att ...

Combining arrays using JavaScript

I'm struggling to enhance the following code - it looks a bit messy: Here is my data format: date d1 d2 d3 d4 d5 d6 110522 5 1 3 5 0 7 110523 9 2 4 6 5 9 110524 0 0 0 0 1 0 110525 0 0 3 0 4 0 ... I am importing data from a text file using d3.j ...

What sets apart elem['textContent'] from elem.textContent?

When dealing with a HTMLElement in JavaScript, is there any distinction between the following lines of code: elem['textContent'] = "Test"; versus elem.textContent = "Test"; This question arises when setting the text content of an HTMLElement. ...

CSS Flexbox: Achieving Perfect Alignment for a Responsive Hamburger Navbar

This is a specific inquiry that requires your attention To begin, kindly execute the code in fullscreen mode Inspect the code and adjust it to fit within a mobile width (there seems to be an issue with responsiveness) Next, open the hamburger menu As show ...

Using a variable to store the value of the id attribute in HTML code

How can I dynamically add an ID attribute to an HTML element using a variable declared in JavaScript? Using jQuery var table_row = $('table').find('tr#' + pid); var name = table_row.find('td:nth-child(1)').html(); table_ ...

Ways to retrieve the content from a textfield

Is there a way to retrieve text from a textfield in material UI without using the onChange method? It just seems odd that I would need to constantly track the value with onChange in order to use it for any other purpose. I decided to search for solutions ...