Implementing checkboxes with identical values in Vue.js

I'm currently working on creating a panel that features multiple checkboxes for users to apply discounts to their cart's total price.

To achieve this, I have implemented a computed function that calculates the difference between the total price and the discount selected via the checkbox.

However, I've noticed an issue where different offers have the same value in the checkbox, causing both of them to be checked when one is clicked.

Can anyone point out what mistake I might be making?

Below is the JavaScript code snippet being used:

const app = new Vue({
el: '#app',
computed: {
    total() {
        return this.fullPrice.reduce( (sum, addon) => sum - addon, 10000);
    }
},
data: {
    fullPrice: [],
    currency: '€',
    offers: [
        {
            id: 'children',
            text: 'Discount for children',
            price: 500
        },
        {
            id: 'senior',
            text: 'Discount for senior',
            price: 100
        },
        {
            id: 'special',
            text: 'Special voucher',
            price: 100
        },
    ]
}
});

You can view the implementation on CodePen here

Answer №1

It is recommended to utilize the entire object as the value for the input element and access the price property.

const application = new Vue({
    el: '#application',
    computed: {
        finalTotal() {
            return this.fullPrice.reduce( (sum, addon) => sum - addon.price, 10000);
        }
    },
    data: {
        fullPrice: [],
        currencyType: '€',
        discounts: [
            {
                id: 'children',
                text: 'Discount for children',
                price: 500
            },
            {
                id: 'senior',
                text: 'Discount for senior citizens',
                price: 100
            },
            {
                id: 'special',
                text: 'Special discount voucher',
                price: 100
            },
        ]
    }
});

View codepen example

Answer №2

Another approach is to trigger a method call in order to update your bindings. However, this method requires a bit of additional coding. Here is the link and code snippet for reference:

https://codepen.io/anon/pen/dVNWNE

<div id="app">
    <h1>Select Your Discount</h1>
    <ul>
        <li v-for="offer in offers" track-by="$index">
            <label>
                <span>{{offer.text}} {{offer.price}}{{currency}}</span>
                <input type="checkbox" :id="offer.id" :value="offer.price"  v-on:input="updateVals($event.target.value)">
            </label>
        </li>
    </ul>
    <p>Total Price: {{total}}{{currency}}</p>
</div>

const app = new Vue({
    el: '#app',
    computed: {
        total() {
            return this.fullPrice.reduce((sum, addon) => sum - addon, 10000);
        }
    },
    data: {
        fullPrice: [],
        currency: '€',
        offers: [
            {
                id: 'children',
                text: 'Discount for Children',
                price: 500,
            },
            {
                id: 'senior',
                text: 'Discount for Senior Citizens',
                price: 100,
            },
            {
                id: 'special',
                text: 'Special Voucher',
                price: 100,
            },
        ]
    },
    methods: {
      updateVals(val) {
        if (this.fullPrice.indexOf(val) === -1) {
            this.fullPrice.push(parseInt(val, 10));
        }
      }
    }
});

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

Sending data using AJAX's XMLHttpRequest POST request

I've successfully used XMLHttpRequest in the past with the GET method, but I'm currently facing challenges trying to implement it using POST. Here's the code snippet: var req = null; if (window.XMLHttpRequest) {// for modern browsers like ...

Expand a div in navigation using JQuery

Check out this code snippet: .container { width: 150px; height: 100px; } .test { color: white; background-color: red; width: 100%; height: 25%; transition: height ease 1s; } .test:hover { height: 100%; } <div class="container"> ...

Leverage the power of jQuery's .filter() method to pinpoint and target specific text

HTML: <p class="greeting"> hello, my name is kevin. what's yours? </p> jQuery: $("p.greeting").filter(function (){ return $this.text() === "my name is"; }).css("background", "green"); I am attempting to find and highlight the phra ...

Need some assistance with Javascript Ajax? Specifically, dealing with multiple values?

My goal is to asynchronously post an array of messages using this code. Despite my efforts, I've encountered a challenge where it doesn't only post the four items in the array but also adds gibberish text. Additionally, there seems to be an issue ...

Utilizing a URL to dynamically update the content within an I-Frame

One day, I made the questionable decision to use i-frames to load pages on my website in order to keep a sidebar on the main page without having to constantly make changes. In hindsight, I should have done the opposite and put the sidebar in the i-frame. N ...

Guide on implementing register helpers with node.js and express handlebars

When loading a record, I have a select option on my form and want to pre-select the saved option. Here is the code: The Student.hbs file displays the form, with the act obj coming from the student.js route student.hbs <form> <div class="for ...

JavaScript variable not refreshing its value after submitting an HTML form

In my HTML form, I have 8 textboxes enclosed in div tags with IDs ranging from fa1 to fa8. By default, two of the textboxes are visible while the remaining six are hidden. To toggle the visibility of these divs, I've implemented two buttons - addfa an ...

Resolving Scope Values in Angular Modal with UI-Bootstrap

I'm fairly new to Angular and I've successfully added a Bootstrap modal to my project. However, I am struggling to retrieve the value from "programcontroller". What I need is the id_program from "programcontroller" inside the "ModalInstanceCtrl" ...

Sending two files to a Node server and retrieving a file through an ajax request

I need assistance with a process involving two file inputs and a button. When the button is clicked, I want to send the two files to the server for processing and then receive a new file as a result. HTML Structure <input id='file-input1' ty ...

Is it possible to include pseudo element elements in the configuration of a custom theme in Material UI?

Within my file themeConfig.js, I have defined several theme variables that are utilized to style different components throughout my application. Among these variables, there is a need for implementing the -webkit scrollbar styles for certain components. Du ...

Exploring the world of Node.js, leveraging the power of Express,

As I embark on a new node.js project, I am eager to enhance the organization of my application. Drawing from my experience with Symfony2 (PHP) and Angular, both of which heavily rely on Dependency Injection (DI), I see the value in applying similar princip ...

How can I conceal a textfield in ReactJS MUI?

I'm working on a textfield that needs some customization. Here is the code: <TextField error={!!errors.imageLink} helperText={errors.imageLink} FormHelperTextProps={{ variant: "standard" }} placeholder="Banner Link&qu ...

React state object iteration doesn't produce any visible output

Trying to dynamically showcase checkboxes with starting values from the state using Material-UI for UI components. tagState: { All: true, Pizza: false, Breakfast: false, Chicken: false } Utilized Object entries and forEach to generate checkbox ...

I am having trouble calling a method in the subscribe function because it is showing an error message saying "Cannot read property 'showMessageFromSocket' of undefined"

My goal is to call a method within the subscribe block, but I am encountering an error that says "Cannot read property 'showMessageFromSocket' of undefined". How can I successfully call the showMessageFromSocket method? In Angular, this was possi ...

Should the autonomous function be halted upon user interaction?

I am working on a carousel that automatically runs, but I also want it to reset its timer if a user interacts with the controls. The current setup does work to some extent, but when interacting with the control-dot, the timer is not reset which leads to un ...

Error encountered when uploading an image using an inertiajs form.post in Laravel 8 due to failed mime image validation

Laravel version: 8.82.0 When using inertiajs, I am facing an issue while uploading an image through a post request using the form.post method. The controller receives image data as shown in the image below: https://i.sstatic.net/pMFTu.png This is my sim ...

What is the best approach to smoothly rotate a cube by 90 degrees in three.js?

Currently, when I rotate the cube using key 'a', 'w', 'd', or 's', the rotation is instant. However, I would like to create a smoother rotating motion so that the user can see the cube twisting gradually, instead of ...

How can I merge my two constants in the handle change function in React and also filter my array?

Currently, I am utilizing React hooks and encountering an issue where the values entered are not being captured when typing. It seems that the input gets reset frequently. Below is the snippet of code illustrating my handle changer function: //handle chan ...

What is the best way to display a unique image in a div based on the size of the

Being new to web design, I have a question about creating a webpage with a large image in the center like on GitHub's Windows page. How can I work with the image inside that particular div or area based on different screen sizes? Is it possible to mak ...

Altering the appearance of a different element with React

I'm new to using react and struggling to make a Component appear when I click on a button. Here's an example of the code I have so far: <Button>GO</Button> <CalendarIcon id="calendar visibility="hidden"/> and th ...