Issue with remove functionality in Vue js implementation causing erratic behavior in my script

Within my Vue.js code, I have a functionality that displays categories from an API. When a category is clicked, it is added to the AddCategory array and then posted to the API. I have also implemented a button called RemoveAll which successfully empties the selected categories in the array. However, I am facing an issue where when I try to click on a selected single category again (in the remove function), it does not get removed from the array but rather gets pushed twice. Can anyone provide assistance?

<template>
  <b-row class="categories-row">
            <div
              class="categories"
              v-for="(category, index) in categories"
              :key="index"
              @click="Add(category._id, index)"
              :class="[selectedIndex.includes(index) ? 'green' : 'gray']"
              required
            >
              {{ category.category_name }}
            </div>
          </b-row>

</template>


export default {
  
  data() {
    return {
      categories: [],
      selectedIndex: [],
      AddCategory: [],
     

      posts: {
        description: null,
        questionTitle: null,
        categories: null,
        
      },
    };
  },
  methods: {
    Add(AddCategory, index) {
         
  if (this.selectedIndex.includes(index)) 
        this.Remove(index); 
      else
      this.selectedIndex.push(index);
      this.AddCategory.push(AddCategory);
    },
      Remove(index) { //not working
      this.selectedIndex.splice(this.selectedIndex.indexOf(index),1);
    },


    RemoveAll() {
      this.AddCategory = [];
      this.selectedIndex.splice(this.AddCategory);
    },}}

Answer №1

Give this a try:

RemoveItem(index) { 
      this.selectedItems = this.selectedItems.filter((item)=> item !== index) ;      
}

Revised:

@sara97 you might want to consider removing it from this.AddCategory method as well.

Revised:

@sara97 and remember, since "this.AddCategory.push(AddCategory);" is executed each time, use {} for if and else conditions.

  Add(AddCategory, index) {
   if (this.selectedItems.includes(index)) {
        this.RemoveItem(AddCategory,index); 
      }else{
      this.selectedIndex.push(index);
      this.AddCategory.push(AddCategory);}
    },

  RemoveItem(AddCategory,index) { 
      this.selectedItems = this.selectedItems.filter((item)=> item !== index);
      this.AddCategory = this.AddCategory.filter((item)=> item !== AddCategory)
    },

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

Capturing user inputs in PHP or AJAX

Is there a way to capture keystrokes on a web page regardless of where the user is focused? For example, if someone has the webpage open and they press '1', can it trigger an action? And if they press '2', can something else happen wit ...

Bootstrap encountered an issue with altering header information

I've been trying to set up a notification system that plays a sound every time someone makes a new post. I'm working with Bootstrap 4 and I've tried inserting JavaScript into the functions page, but no matter how many times I call the ' ...

After clicking on the checkbox, req.body.task becomes undefined

Whenever I click on the checkbox, the value of req.body.task returns as undefined. <input type="checkbox" name="task" autocomplete="off" checked="" onchange="onToDochange({{id}})"> This function is triggered by a change event on the checkbox and it ...

Using axios to make a request from a server to itself

I'm facing an issue where I am attempting to send a request from the server to the same server using axios as a PUT method. Here is an example of what I have tried: await axios({ url: `http://localhost:4000${url}`, method: requestType, ...

Having trouble displaying HTML UL content conditionally in Reactjs?

My goal is to display a list of items, limited to a maximum of 5 items, with a "more" button that appears conditionally based on the number of items in the list. However, I am encountering an issue where passing in 5 li items causes them to be rendered as ...

Issue with pop-up functionality on web page using HTML, CSS, and JavaScript

Recently, I created a unique popup using HTML. You can see the complete code (excluding CSS) here: https://codepen.io/nope99675/pen/BawrdBX. Below is the snippet of the HTML: <!DOCTYPE html> <html> <head> <meta charset=&quo ...

Appium with Node.js (wd) becomes unresponsive when unable to locate element

Encountering an issue while using appium with nodejs (wd) and mocha, as there is a loading view in the android app (blackbox testing & I'm not the developer) that needs to be waited for its disappearance. Attempted the following solution: wd.addPromi ...

Looking to develop a dynamic password verification form control?

I am in the process of developing a material password confirmation component that can be seamlessly integrated with Angular Reactive Forms. This will allow the same component to be utilized in both Registration and Password Reset forms. If you would like ...

Utilizing dynamic meta tags in React JS with a PHP backend and Redux integration

Adding dynamic meta data like title, description, og_image, etc. in reactJs can be a bit complex. I've tried using the react-meta-tags package which changes the title and updates the meta data visible in my browser Inspector. However, when sharing on ...

How can I display several custom markers that are constantly updating on a Google map with MySQL and PHP?

Currently, I am using the following code to generate markers on a Google map by retrieving data from a database. However, the issue I am facing is that it only generates one marker instead of all the markers stored in the database. & ...

The error message "Cannot access property 'findAll' of undefined in expressjs" is displayed

An issue has occurred with ExpressJS: TypeError - Cannot read property 'findAll' of undefined. It seems that all Sequelize functions are not working correctly. Numerous errors are popping up, such as "Cannot read property 'sequelize method& ...

Organizing Angular project folders with the help of Node.js and Jade

I've been exploring different folder structures to ensure scalability as my project grows. While I found some useful resources, such as this one, I'm still struggling with how to actually implement these suggestions. Currently, I've adopted ...

Troubleshooting Compatibility Issues: JavaScript Function Works in Chrome but not in Internet

After collaborating with fellow coders to develop info boxes using HTML, CSS, and JavaScript, I have come across an issue with the hover functionality not working properly in Internet Explorer. Interestingly, everything functions flawlessly on Google Chrom ...

The appearance of HTML dropdown select options is unappealing when viewed on iPhones

Looking for a simple alternative to the dropdown menu implementation on iPhones/iOS for a mobile website (not native app). Any suggestions using HTML/CSS/JavaScript? <!DOCTYPE html> <html> <head> <meta name="viewport" content="initi ...

Extend JavaScript capabilities for window.print() function to automatically include backgrounds

I am looking to add a special magical property to my Print this Page button. This property will automatically enable the default unset option (shown in the picture) which is to print the backgrounds of div colors and background images. <a href="#" oncl ...

Is there a way to display a different file, such as index.html, based on the screen width?

I'm facing an issue. I have completed a web page (with HTML, CSS, and JavaScript), but now I want to create a mobile version using different HTML files, another index.html file, and a separate CSS file. What changes do I need to make in the main page ...

Present pop-up messages in the most sophisticated manner

I have successfully created an AngularJS app that is functioning well. Now, I am faced with the challenge of displaying different pop-ups based on specific conditions being met. I am unsure of the best approach to take. Currently, I am considering two op ...

Nested JSON array is being shown as [Object Object] within a TextField

I am facing an issue with mapping two sets of JSON data, which I will refer to as Set 1 and Set 2. In Set 1, the data (named sizingData) is being mapped to text fields using the following function: const fillTextField = () => { let result = []; ...

What is the reason for the maximum alias number in the npm YAML library?

I have been utilizing the npm module yaml to convert complex, interdependent JavaScript objects into a text format that can be easily restored in Javascript. Additionally, I use this package for deep copying of deeply nested objects by serializing and then ...

The conditional statement for multiplying in JavaScript

I have a JavaScript function that selects a report number based on multiple parameters (2 checkboxes, 3 dropdown fields), and the current implementation involves a complex conditional statement as shown below: switch(ReportNumDrop) { case 0 ...