The ".splice()" method continuously removes the final element from an array

I have implemented a function on my form that allows me to add multiple file inputs for various images by clicking a button. Although this functionality is working correctly, I am facing an issue while trying to delete an input field using .splice. Instead of deleting the input field with the matching index, it keeps removing the last item in the array where my input fields are stored. Despite spending hours attempting to resolve this problem, I am unable to find a solution. I would greatly appreciate any help or advice on what might be causing this error.

Here is the method used to add a new input field:

addInputField() {

    i++

    this.values.links.push({
      id: i,
      url: ''
    });
  }

This is the code snippet responsible for deleting an input field:

deleteInputField(index) {

    this.values.links.splice(index, 1);

    const items = this.values.links.filter(item => {

      return item.id > index
    });

    items.forEach(function (item) {
      item.id = item.id -1;
    });
  }

Below is the button used to delete the input field:

<v-icon
  medium
  v-if="link.id > 0"
  color="#FF0000"
  class="ma-4"
  @click="deleteInputField(link.id)"
>

Answer №1

To easily remove the id (link.id), you can utilize this convenient function.

function eliminateLinkEntry(linkId){
    this.data.links = this.data.links.filter(entry => {
        return entry.id !== linkId;
    });
}

By using this code, it will iterate through the array and exclude the one with the same id as the specified linkId.

Alternatively, you can directly pass the index from the v-for loop to the @click event handler.

eliminateLinkEntry(index) {
    this.data.links.splice(index, 1);
}

Answer №2

hyperlinks represents a collection of objects. The parameter passed is not an index within the array, but rather an identifier found inside the nested object.

<v-icon
  medium
  v-if="link.id > 0"
  color="#FF0000"
  class="ma-4"
  @click="deleteInputField(link.id)" // Modify to use index (mostly obtained from v-for loop)
>

Answer №3

When using the splice method, it's important to understand that the first parameter is known as start:

This refers to the index at which the changes to the array should begin. If this index is larger than the length of the array, the starting point will default to the end of the array. In cases where the index is negative, the starting point will be relative to the end of the array (using -1 as the origin point). For example, a value of -n indicates the nth last element from the end, equivalent to array.length - n. If the sum of array.length and the start value is less than 0, the starting point will be set at index 0.

Upon closer inspection of the code, you'll notice that the id being passed is not an actual index in the links array. Instead, it corresponds to an id greater than the array's length.

Answer №4

If you want to delete a specific input field, remember that the ID is not the same as the index. You can remove the desired input field by using the following code:

this.values.links.splice(index, 1);

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

Guide to implementing final state injection using Vue Server-Side Rendering (SSR) and V8Js

The Vue SSR guide primarily focuses on setting up a nodejs server and briefly discusses using V8Js in the final chapter. While there is a section dedicated to final state injection, it doesn't seem to be compatible with V8Js. Is there a way to trans ...

ng-class not functioning properly when invoked

In my controller, I have the following function: $scope.menus = {}; $http.get('web/core/components/home/nav.json').success(function (data) { $scope.menus = data; $scope.validaMenu(); }).error(function () { console.log('ERRO') }); ...

Tips for delaying my response in nodejs until the loop is complete

This is the code I'm currently working with: myinsts.forEach(function (myinstId) { Organization.getOrgById(myinstId,function (err, insts) { res.json(insts); }) }); I am using Node.js and encountering an error message that says "Can't set hea ...

JavaScript and JSON interchangeably, the first AJAX response should be rewritten by the second response

I am facing an issue with my code: I have two ajax calls being made on window.load, and it seems like the response from the second AJAX call is overwriting the response from the first one before my function can process it. I'm not sure where I'm ...

Utilizing the Vuetify Dialog Component in a repetitive manner to confirm the deletion of an event

In a project I'm working on, there's a 'datatable.vue' file that loops through data and displays it in a table. Within this loop, I want to implement a reusable dialog component from Vuetify (v-dialog) that will load upon interaction wi ...

Using Vue slots in a loop to create a unique slider component

I'm struggling to figure out how to utilize slots for a SliderA component. The structure of SliderA component is as follows, with slides being an array prop. <template> <div class="slider-container" ref="container"> ...

Error encountered: Cordova plugins return undefined values when testing on an actual device

I am currently utilizing Phonegap in conjunction with ngCordova and AngularJS. The aim is to leverage the capabilities of the plugin (PhoneGap-Image-Resizer) to facilitate media saving on the device. However, I encountered an issue where the plugin throws ...

Duplicate request submissions in ExtJs causing inefficiency

Trying to resolve an issue with my ExtJs table that handles remote filtering, sorting, and paging of data on the server. The problem arises when a default request is being sent alongside every other request: localhost/request?page=1&start=0&limit= ...

Populate a table dynamically using JavaScript based on existing cell values

I am currently working on filling an HTML table based on the contents of its left cells. The code below creates a table that is populated with variables: <table id="myTable" ></table> <script> var rightcell = [{name : "Name ...

Using Vue.js to create dynamic routes that fetch and utilize a unique parameter ID

user/index.vue <tbody> <tr v-for="item in items" :key="item.id" > <td v-if="false" v-text="item.id" /> <td v-text="item.name" /> ...

How can I render just one event instead of all events when using the eventRender callback function?

I am currently working on adding an event to my calendar using a JSON format with specific attributes like id and start time. Here is what I have tried so far: $('#calendar').fullCalendar('renderEvent', my_event); $('#calendar& ...

Ensure that the array of JSON objects is a subset of another array of JSON objects

I am looking to compare each array in testEdge with newarr and find the matching id for each array in testEdge const testEdge = [ [{ id: '0', from: '0', to: '1' }, { id: '1', from: '1&ap ...

Achieving a Transparent Flash overlay on a website without hindering its usability (attention, interaction, form submissions, etc.)

Currently, we are attempting to overlay a transparent flash on top of an iframe which loads external websites. Is there a method to configure the page in a way that allows the transparent flash to be displayed while still allowing interaction with the und ...

What is the best way to place text inside a TH element without any text within the TH's child nodes?

When parsing a website and obtaining the instance of a TH element, I use innerText to extract the text I need. However, sometimes there is additional unnecessary text that I want to exclude. Is there a way to only retrieve the top-level text? var th_elem ...

showcasing recommended options in the search bar through the use of javaScript

Hey there, I've been working on creating result suggestions for my search bar. The generation process is all set, but I'm facing an issue with displaying the elements on the HTML page. During testing, I keep seeing ${resultItem.name}, and when I ...

Does the "onevent" option get disregarded for jsf.ajax.request in JSF

In my attempt to develop an interactive chat web application using Java EE 7, I am specifically utilizing JSF 2.2 with ajax. The concept involves having a slow pending asynchronous ajax request waiting on the server for each unique client. When a new mess ...

Update Button Visibility Based on State Change in ReactJS

Currently, I'm utilizing a Material UI button within my React application. Despite changing the state, the button remains visible on the screen. Here's the relevant code snippet: function MainPage() { const state = useSelector(state => sta ...

Problem with AngularJS Multiselect checkbox dropdown configuration

In my application, I have a pop-up that includes a multi-select dropdown menu. Here is the code for the Multi-Select Dropdown: <select name="edit_tags" class="form-control" id="advisor_article_tagsx" multiple="" required ng-model="article_selected ...

Looking to have two separate modules on a single page in AngularJS, each with its own unique view

<!DOCTYPE html> <html> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js" ...

Error occurred while attempting to upload a file using multipart form data: TypeError message displayed - Unable to access properties of undefined (specifically '0')

I am encountering an issue while trying to send multipart/form-data using axios from the frontend. The same post request works fine in Postman/Insomnia but fails when executed from the frontend. The backend shows the following error: node:events:505 ...