Click the checkbox to add or remove data

I am currently facing a situation where I have multiple checkboxes and upon clicking any of them, the value is added to an array. If the checkbox is unchecked, then the item should be removed from the array.

selectAddOn(addOnId) {
    if (! this.selectedAddOns.includes(addOnId)) {
        this.selectedAddOns.push(addOnId);
    }
}

The code above successfully adds the values to my selectedAddOns[]. However, the issue arises when trying to remove the value if the checkbox is checked again. While using else could work, there's a complication due to browser behavior.

When clicking on a <label>, a click event is automatically triggered on the <input>, causing the outer div to receive two events - one from label and one from input. Although adding @click.prevent on the <label> can resolve this, it interferes with custom checkbox styling.

<div @click="selectAddOn(index)" class="col-6" v-for="(addOn, index) in categories[categoryId].addOns">
    <label class="custom-control custom-checkbox">
        <input type="checkbox" class="custom-control-input">
        <span class="custom-control-indicator"></span>
        <span class="custom-control-description">{{ addOn.name }} (+ ${{ addOn.price }})</span>
    </label>
</div>

Do you have any suggestions on how to address this challenge?

Answer №1

When utilizing v-model with an array on multiple checkboxes, the behavior is inherent and does not require a separate click handler. (Credit goes to Bert's answer for the code snippet below.)

console.clear()

new Vue({
  el: "#app",
  data:{
    selectedAddOns:[],
    categories:[
      {
        addOns:[
          {name: "AddOn One", price: 10},
          {name: "AddOn two", price: 20},
          {name: "AddOn Three", price: 30},
        ]
      },

    ],
    categoryId: 0
  }
})
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="483e3d2d087a667c667a">[email protected]</a>"></script>
<div id="app">
  Selected Addons: {{selectedAddOns}}
  <div class="col-6" v-for="addOn, index in categories[categoryId].addOns">
    <label class="custom-control custom-checkbox" >
        <input type="checkbox" class="custom-control-input" :value="index" v-model="selectedAddOns" >
        <span class="custom-control-indicator"></span>
        <span class="custom-control-description">{{ addOn.name }} (+ ${{ addOn.price }})</span>
    </label>
</div>
</div>

Answer №2

Make sure to attach the click event handler onto the input.

console.clear()

new Vue({
  el: "#app",
  data:{
    selectedAddOns:[],
    categories:[
      {
        addOns:[
          {name: "Additional Option One", price: 10},
          {name: "Extra Feature two", price: 20},
          {name: "Special AddOn Three", price: 30},
        ]
      },

    ],
    categoryId: 0
  },
  methods:{
    chooseAddOn(addOnId) {
      let position = this.selectedAddOns.findIndex(item => item === addOnId)
      if (position >= 0) 
        this.selectedAddOns.splice(position, 1)
      else 
        this.selectedAddOns.push(addOnId);
    }
  }
})
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2254574762100c160c">[email protected]</a>"></script>
<div id="app">
  Chosen Addons: {{selectedAddOns}}
  <div class="col-6" v-for="(addOn, index) in categories[categoryId].addOns">
    <label class="custom-control custom-checkbox" >
        <input type="checkbox" class="custom-control-input" @click="chooseAddOn(index)" >
        <span class="custom-control-indicator"></span>
        <span class="custom-control-description">{{ addOn.name }} (+ ${{ addOn.price }})</span>
    </label>
</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

Eliminate duplicate entries in typeahead.js by ensuring unique data sources for both prefetch and remote

Currently, I have implemented typeahead.js with both prefetch and remote data sources. You can check out the example here. $(document).ready(function() { var castDirectors = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('val ...

The navigation functionality in vue.js is experiencing issues with the router integration

As I work on securing my routers in vue.js, I have implemented user authentication to restrict access to unauthorized users. However, I encountered a loophole where a logged-in patient could access the profile of a doctor by navigating to the respective ro ...

Tips for sorting through values that may occasionally lack definition:

I am currently working on an application that involves a tree structure of various objects. Each object has a unique ID and the possibility of having a parent object. Unfortunately, I am facing an issue with the standard filter syntax when the current ID ...

If viewed on a mobile device, separate the array (indexed list) into two rows

Currently, I am working on my Ionic project where I am trying to implement an indexed list horizontally instead of vertically. While the list looks good as it is now, I want to make sure it supports smaller screen devices too by splitting the list into two ...

Vue.js bootstrap-vue input number has a unique MaxLength feature that sets the

Is there a way to limit the input length for an input field from bootstrap-vue? I tried using maxLength, but it seems that it's not supported based on their documentation. If I remove type="number", the limitation works, but then it won't restric ...

Preventing duplication of code execution in recycled PHP elements

Currently, I have implemented a generic toolbar that is used on multiple pages of my web application by using PHP include. This toolbar contains log in/log out functionality and checks the log in status upon loading to update its UI accordingly. Initially ...

The Java Servlet change did not trigger an update in the web content

While using Eclipse to develop a website where Servlet sends data to JSP, I encountered an issue. Despite modifying the data in the Servlet, it continued to send outdated information to the JSP page. I attempted the following options: Menu - Project - cle ...

What could be causing my Graphql query to return a null value?

I have been working on setting up a GraphQL application to access data from games.espn.com. However, I am facing an issue where my queries are returning null values. I suspect that there may be something missing in terms of return or resolve functions in t ...

Executing PHP code upon user click and transmitting variables

After receiving an answer from a previous question, I am using the code below: <script type="text/javascript" src="jquery.min.js"></script> <script type="text/javascript> function doSomething() { $.get("somepage.php"); return fal ...

In the realm of programming, the term "is not a function" can be

I've been working on creating an HTML button that triggers a function called switch_user, but when I click it, the console keeps saying that switch_user is not a function. Here's the button in question: <input type="button" class="btn btn-lo ...

How come my test is returning a status code of 200 when the token is not included?

Before each test implementation, I defined let token and logged in. However, in this specific case, I simply set token = '' to ensure that the client is not logged in. My expectation was to receive a status code of 401, but instead, I am receivin ...

What methods are available to change one JSON format into another?

I am receiving JSON data from a Laravel API in the following format: [ { "id":48, "parentid":0, "title":"Item 1", "child_content":[ { "id":49, "parentid":48, "title":"Itema 1 ...

Node.js axios and async await pattern utilized for downloading arrays of files in vanilla JavaScript

I am encountering an issue with a script written in vanilla JavaScript that runs in Node.js. The desired outcome is as follows: // Get axios request // response stream // download file1..........finish // When file is downloaded // go to the next req ...

Are there any issues with integrating the Bootstrap 4 Datepicker script?

I'm having trouble getting a simple bootstrap datepicker to work on a large page despite including all the necessary scripts and stylesheets. Here is my code: <html> <body> <div id="datepicker" class="input-group d ...

Is it necessary to test the Javascript webservice API?

Currently, I am in the process of testing my REST API using should. So far, I have successfully tested my methods through both browser and console testing. When it comes to testing with should, my test cases for GET methods from the API are working perfe ...

What causes the scrollTop to appear erratic?

There is a simple issue that I find difficult to explain in text, so I have created a video demonstration instead. Please watch the video at this link: The functionality on my page works perfectly when scrolling down, as it replaces images with the next i ...

Utilize one ajax response for three distinct sections/divisions

After making an ajax call, I am receiving a total of 27 results that I need to divide equally into three sections, with 9 results in each. The sections are displayed below: HTML: <div id="content"> <section> </section> <s ...

Enhance your website with a dynamic 'click to update' feature using ajax

I'm in the process of developing a straightforward list application where users can easily edit items by clicking on them. Although everything seems to be working fine, I'm encountering an issue with saving changes to the database. For some reaso ...

Using PHP to pass variables to an external JavaScript file

I have come across the following code snippet: PHP <?php include("db.php"); ?> <html> <head> <title>Title</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/j ...

JavaScript library for making HTTP requests

Can someone provide guidance on creating a JavaScript command line application that interacts with a public API using an HTTP client library? What is the preferred JavaScript HTTP library for this task? ...