Implementing Vue.js functionality to dynamically add or remove values from an array based on the state of a checkbox

I recently embarked on my journey to learn vue.js and I've encountered a challenging issue. I have dynamic data that I render using a 'v-for' loop. Additionally, I have an empty array where I need to store checked checkbox data and remove it upon unchecking. Moreover, I am striving to update this array when any object's data is modified. For instance, if I add the first object to the empty array and then adjust the quantity value, I don't want to create a new object but rather update the existing one.

const app = new Vue({ 
  el: '#app', 
  data: () => ({ 
  
   products:[
 { itemId:'330012929', name:'testBook', cashBack:'3.00', price:12.99, quantity:1},
  { itemId:'330012922', name:'testBook2', cashBack:'4.00', price:12.2, quantity:1},
     ]
  }),
  
  methods:{
    pushValue(arg){
     console.log(arg)
    }
  }
 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
   <div v-for='(x,index) in  products' :key='index'>
      <div><span><input type='checkbox' @change='pushValue(x)'><span>item id: {{x.itemId}}</div>
   </div>
</div>

Answer №1

    <ul class="category__list">
      <li v-for="(genre, value) in genresList[genreTitle]" :key="value">
        <input type="checkbox" :value="genre" v-model="selectedGenres"&rt; 
               {{genre}}
      </li>
   </ul>

By using v-model on checkbox input and defining it as an array, Vue will handle everything for you automatically. The SelectedGenres array will contain the checked checkboxes.

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

Turn off the perpetual active mode

I have a situation where a link maintains its active state after being dragged and released. This is causing an issue that I need to address. For example, you can see the problem here: http://jsfiddle.net/Ek43k/3/ <a href="javascript:void(0);" id="foo ...

Leverage ObjectMapper for parsing nested Dictionaries in Swift

My previous JSON format looked like this: { "parameters": { "customerId": 9, "from": "2014-06-05T14:00:00", "until": "2014-06-05T15:00:00", "km": 20, "insurance": false }, "estimatesPerCategory": { "2": { "timeCost": 5, "kmCost": 6, ... } For ...

Generate instances of the identical class with distinct attributes

Is it possible in Java to create objects of the same class with different variables each time? For instance: I have a method that retrieves data from a URL containing a JSON file, and I want to use this data to create a post object. ObjectMapper mapper ...

Navigating within a React application using React Router 2.6.0 by triggering a redirection within a click

Currently, I am experiencing an issue while utilizing react-router for constructing a login system with firebase and react. The desired functionality involves redirecting the user to the home page upon successful authentication of their username and passw ...

Executing a component's method using HTML in Vue2

In my development project, there is a .vue file named ServiceList. This file imports the component called Information.vue. My objective is to execute the code from the Information component in a loop within the template of the ServiceList file. Here is an ...

What is the best way to calculate the percentage of a quantity within the <td> tag?

I am trying to calculate the percentage of quantity per day by summing up all quantities and then dividing each quantity by the total sum. However, when I combine these calculations in my HTML code using distributed.Quantity, I end up with a NaN value. How ...

Learn how to clear the data in a Select multiple field while typing in another text field with reactjs

I have a current code snippet that I need help with. After selecting an option from the dropdown menu (CHIP), if the user starts typing in the text field, I want to clear the selection made in the CHIP. How can I achieve this functionality? const names = ...

What is causing the navbar to malfunction on mobile devices?

I am facing an issue with my bootstrap navbar. It seems to be getting stuck when the screen resizes or when viewed on a mobile device. I have tried several solutions from various sources, but none seem to work. Here are some of the answers that I have look ...

Guide on making jQuery color variables?

Is there a way to achieve CSS variable-like functionality with jQuery? For example, creating reusable CSS attributes in jQuery instead of using SASS variables. Imagine if I could define a variable for the color black like this: I want to make a variable t ...

Tips for modifying the class of a span inline element using a javascript function

Looking for assistance in creating a password text box with an eye icon that toggles visibility. When the user clicks on the eye icon, it should change to a crossed-out eye icon and switch the input type to text. <div class="input-group show-hide-passw ...

Pagination of AJAX result on the client side using jQuery

My issue revolves around pagination in AJAX. I want to avoid overwhelming my search result page with a long list of returned HTML, so I need to split it into smaller sections. The Ajax code I am currently using is: $.ajax({ url: "getflightlist.php?pa ...

Passing string values to an onClick event listener in Javascript is similar to how it is done in an onclick event listener in HTML

render() { return ( <div> <div onClick={() => "FSR.launchFeedback('ax9sgJjdSncZWoES6pew6wMIyCgSXpC')" } /> </div> ); } This piece of code initially appear ...

Running Python in React using the latest versions of Pyodide results in a malfunction

As someone who is new to React and Pyodide, I am exploring ways to incorporate OpenCV functionality into my code. Currently, I have a working piece of code that allows me to use numpy for calculations. However, Pyodide v0.18.1 does not support OpenCV. Fort ...

Issues with Vue Sortable functionality may be causing complications

Currently, I am utilizing vue-sortable and draggable. Although I am able to drag an item above and change its position, the JSON data does not refresh. Here is the existing list: <draggable v-model="this.$store.getters.getDocument.getDocumentAttributes ...

Ways to retrieve the user's IP address and provide the information in JSON format

Although I am not an expert in PHP, I specialize in developing Android apps. One of the challenges I face is extracting the user's IP address from a specific URL . This URL provides various information when accessed, but my main requirement is to retr ...

Improper Alignment of Bootstrap 4 Navbar Link: Troubleshooting Required

Take a look at the image for the issue: https://i.stack.imgur.com/u9aCy.png As shown in the image, the NavBar links are stacked instead of being displayed in one row. This is the HTML code I have used: <!doctype html> <html> <head> ...

"react commands" are not recognized as an internal or external command by any program or batch file

Initially, everything was working smoothly until I decided to download some updates from the git repository. However, upon execution, I encountered an error message stating that "react scripts" are not recognized as an internal or external command, operabl ...

Is there a way to establish a condition for an onSubmit event?

I have a form that I'm working on, and I would like for an error message to pop up upon the first onSubmit, and then function normally on subsequent submissions. Here is the current setup: const [submitting, setSubmitting] = useState(false); const ha ...

Rails - implementing ajax in partials causing an error: 'cannot find method render'

I am encountering an issue with my form partial located within a div that has the id "chapcomments". The form includes a submit button: <%= f.submit "Post", remote: true %> Within the correct view folder, I have a file named create.js.erb which con ...

When using DataContractJsonSerializer, you can deserialize an object that may either be a string or an object

Currently, I am fetching data from an API that sends me an array. The "params" object is a string in the first element and an object in the second one. Here is how my DataContract looks: [DataMember(Name = "params")] string Params; [DataMember(Name = "p ...