Remove input fields that were generated upon clicking a button

I'm facing an issue with my code that allows me to add inputs using @click="addInput()". However, I am struggling to delete specific inputs using @click="deleteInput(). When I try to delete an input with this.inputs.splice(index, 1), only the last input gets deleted and I can't figure out why.

Can anyone provide a solution on how to delete a specific input instead of just the last one?

It's important to note that the additional code in my inputs at addInput involves the name property from a child element.

Thank you for your assistance!

Here is a snippet of my template:

<template>
  <div >
    <div class="mt-2" v-for="(id, index) in inputs" :key="index">
      <div class="row mb-3">
        <b-button-group class="col-md-12">
          <b-button class="col-md-8" v-b-toggle="toggleElementInChildVue" variant="danger"></b-button>
          <b-button @click="deleteInput(index)" class="col-md-4" variant="danger">Delete this!</b-button>
        </b-button-group>
      </div>
    </div>

    <div>
      <b-button @click="addInput()">Add Input</b-button>
    </div>
  </div>
</template>

And here is my script section:

<script>
export default {
  name: 'test',

  data() {
    return {
      inputs: [{
        name: "",
      }],
    }
  },

  methods: {
    deleteInput(index) {
      this.inputs.splice(index, 1)
    },
  
    addInput() {
      this.inputs.push({
        name: "",
      })
    },
  },  
}
</script>

Answer №1

It appears that your delete function is functioning correctly. Please review the following code snippet:

new Vue({
  el: '#demo',
  data() {
    return {
      inputs: [{
        name: "aa",
      }],
    }
  },

  methods: {
    deleteInput(index) {
      this.inputs.splice(index, 1)
    },
  
    addInput() {
      this.inputs.push({
        name: "bb",
      })
    },
  },  
})

Vue.config.productionTip = false
Vue.config.devtools = false
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.css" />

<!-- Load polyfills to support older browsers -->
<script src="//polyfill.io/v3/polyfill.min.js?features=es2015%2CIntersectionObserver" crossorigin="anonymous"></script>

<!-- Load Vue followed by BootstrapVue -->
<script src="//unpkg.com/vue@latest/dist/vue.min.js"></script>
<script src="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.js"></script>

<!-- Load the following for BootstrapVueIcons support -->
<script src="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue-icons.min.js"></script>

<div id="demo">
  <div >
    <div class="mt-2" v-for="(name, index) in inputs" :key="index">
      <div class="row mb-3">
        <b-button-group class="col-md-12">
          <b-button class="col-md-8"  variant="danger">{{name}}</b-button>
          <b-button @click="deleteInput(index)" class="col-md-4" variant="danger">Delete this!</b-button>
        </b-button-group>
      </div>
    </div>

    <div>
      <b-button @click="addInput()">Add Input</b-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

Ensure that the search input field is in focus whenever the showSearch state is true

Having difficulty focusing on the input field whenever the showSearch state is true. Utilizing useRef and useEffect for this purpose. When the showSearch flag changes, the useEffect hook is triggered to check if showSearch is true, and if so, it should foc ...

Converting TypeScript to ES5 in Angular 2: A Comprehensive Guide

I am currently diving into Angular 2 and delving into Typescript to create simple applications within the Angular 2 framework. What I have discovered is that with Typescript, we can utilize classes, interfaces, modules, and more to enhance our application ...

The function call to 'import firebase.firestore()' results in a value

I recently set up a Vue App with the Vuefire plugin. Here is an example of my main.js file, following the documentation provided at: : import Vue from 'vue' import App from './App.vue' import router from './router' import sto ...

Having trouble with my basic AJAX request; it's not functioning as expected

I am currently diving into the world of Ajax and I've hit a roadblock: 1. HTML : <body> <form> Username: <input type="text" id="username" name="username"/> <input type="submit" id="submit" /> </form> <scrip ...

Tips for seamless communication between PHP and JavaScript

While working on my revolutionary WebIDE, I encounter numerous questions that challenge me. The goal of this project is to assist users in quickly developing what they normally would, but automated. One particular question I have is regarding the implement ...

Encountering a Typescript error while attempting to remove an event that has a FormEvent type

Struggling to remove an event listener in Typescript due to a mismatch between the expected type EventListenerOrEventListenerObject and the actual type of FormEvent: private saveHighScore (event: React.FormEvent<HTMLInputElement>) { This is how I t ...

Developing a Multi-Faceted Array Utilizing SQL Data

The requirement of the plugin I am using is to provide it with an array structure in JavaScript that looks like this: var data = [ { "id": 1, "name": "University1", "list": [ {"id": 1, "name": "Dorms", "list": ...

Currently, my nextjs project is up and running smoothly in vscode. When I execute `npm run dev` in the terminal, everything seems to be working fine. However

Whenever I run npm run dev in my terminal to start a nextJS project, it shows the following output: > [email protected] dev > next dev ready - started server on 0.0.0.0:3000, url: http://localhost:3000 but when I try to access it in the browser, ...

What are the advantages of utilizing buffer geometries in Three.js?

I have experience using both BufferGeometry and Geometry, so I feel comfortable with either. Even when I need to make frequent modifications, I tend to lean on BufferGeometry because although the code is more verbose, it's not overly complex. Can you ...

What is the syntax for creating a link tag with interpolation in Angular 2 / Ionic 2?

As I work on developing an app using Ionic 2/Angular 2, I have encountered a challenge that I am struggling to overcome. Let me provide some context: I am retrieving multiple strings from a webservice, and some of these strings contain links. Here is an e ...

React web app experiencing an issue with MUI Drawer opening flawlessly but failing to close

Recently, I encountered an issue with my React app. I have a Navbar component that displays a Sidebar component when the screen is small, using Material UI for the Drawer functionality. The problem arises when clicking the hamburger icon to open the drawe ...

php json with multiple dimensions

Unable to retrieve the deepest values from my json object, which contains an array of images listed as: { "imgs":[ { "Landscape":{ "2":"DSCF2719.jpg", "3":"DSCF2775.jpg", "4":"IMG_1586.jpg", ...

Observing a global object's attribute in Angular JS

Imagine you have an object in the global scope (yes, I know it's not ideal but just for demonstration purposes) and you wish to monitor a property of that object using Angular JS. var person = { name: 'John Doe' }; var app = angular.mod ...

Error Module in Angular 1.4.2: $injector:modulerr

I have exhausted all the solutions available on StackOverflow and other sources, but none of them seem to work for me. I have ensured that all scripts are loaded properly. I am using Visual Studio 2015 and trying to create a menu using Mobile Angular Ver ...

Omitting authentication request in Laravel Echo server CLI on the server

Everything runs smoothly on my local machine, but for some reason it's not working on the server. Image from my local environment Image from the server I am using Laravel 5.8 and Vue.js. The domain is HTTPS encrypted. ...

Utilizing the "each" function in jQuery to create click events for buttons that are linked to specific paragraphs

Right now, I am facing a situation where I have three buttons, each assigned with an ID that matches their order. Upon clicking a button, the paragraph associated with that order should hide itself using .hide(). My challenge lies in finding out how to ut ...

Hovering over the child element, instead of the parent

I'm working on implementing a highlight feature for my website. The structure of the HTML looks something like this: <div> <!-- this is the main container --> <div> content ... </div><!-- a child element --> < ...

Transform the binary image data sent by the server into an <img> element without using base64 encoding

It's been a challenge trying to find a reliable method for adding custom request headers to img src, so I'm experimenting with manually downloading the image using ajax. Here is an example of the code I am working on: const load = async () => ...

The $route.reload() function seems to be ineffective in Internet Explorer

I'm currently using AngularJs to develop an application. The issue I am encountering is related to data not being refreshed in IE, even after executing the $route.reload() function. Strangely enough, this problem only occurs in Internet Explorer and w ...

The success:function() is not being triggered in the Ajax response with jQuery version 1.8.3

My code is not calling success:function() in the Ajax response when using jQuery 1.8.3, but it works perfectly with jQuery 1.4.2. Here is the code snippet: <script type="text/javascript"> $(document).ready(function(){ $("#usn").on('keyup&a ...