Organizing checkboxes to store selected values in an array using Vue.js

I am looking to implement a feature where a user can select checkboxes from a grouped list populated by an API call. When a checkbox is selected, I want to add the corresponding object to an array linked to the v-model of the checkbox input. Below are the details of the data fed into the checkboxes and my VUE and HTML code.

  "data":[
      {
         "customerId":"046094",
         "coreSystem":"symplusAM",
         "accountId":"MMF046094001",
         "fundName":"UNITED CAPITAL MONEY MARKET FUND"
      },
      {
         "customerId":"046094",
         "coreSystem":"symplusAM",
         "accountId":"SIS046094001",
         "fundName":"UNITED CAPITAL STAFF INVESTMENT SCHEME"
      },
      {
         "customerId":"046094",
         "coreSystem":"symplusAM",
         "accountId":"EUROB046094001",
         "fundName":"UNITED CAPITAL NIGERIAN EUROBOND FUND "
      }
  ]

VUE Code:

<div style="padding-top:40px;" class="col s3">
                <div class="input-field">
                    <h6 class="left-align">Select Portfolio Accounts</h6>
                    <template v-for="(item, key, index) in portfolioList">   
                        <p>
                            <label>
                                <input v-model="selectedPortfolios[item]" :value="item"  type="checkbox" class="filled-in" />
                                <span>
                                    {{ item.fundName }}                                 
                                </span>
                            </label>
                        </p>                  
                </template> 
                </div>
            </div>

I aim to update the selectedPortfolios array with specific fields - "customerId":"046094","coreSystem":"symplusAM","accountId":"MMF046094001" whenever a checkbox is ticked. How can I achieve this functionality in Vue?

Answer №1

To implement a check on an object, you can simply add a property that signifies the checking status, which can then be used to generate a computed value.

For example:

  <input
    v-model="item.$_checked"
    type="checkbox"
    class="filled-in"
  />

and

  computed: {
    selectedPortfolios()
    {
      return this.portfolioList.filter(item => item.$_checked);
    }
  },

You can view the code in action on codesandbox: https://codesandbox.io/s/tender-haslett-5658h?file=/src/App.vue:278-422

<template>
  <div id="app">
    <div style="padding-top:40px;" class="col s3">
      <div class="input-field">
        <h6 class="left-align">Select Portfolio Accounts</h6>
        <template v-for="(item, index) in portfolioList">
          <p :key="index">
            <label>
              <input
                v-model="item.$_checked"
                type="checkbox"
                class="filled-in"
              />
              <span>{{ item.fundName }}</span>
            </label>
          </p>
        </template>
      </div>
    </div>

    <div>
        <header>Selected</header>
        <div v-for="(portfolio, key, index) of selectedPortfolios" :key="index">
          {{ portfolio.fundName }}
        </div>
    </div>
  </div>
</template>

<script>
import HelloWorld from "./components/HelloWorld";

export default {
  name: "App",
  components: {
    HelloWorld
  },
  computed: {
    selectedPortfolios()
    {
      return this.portfolioList.filter(item => item.$_checked);
    }
  },
  data() {
    return {
        "portfolioList":[
      {
         "customerId":"046094",
         "coreSystem":"symplusAM",
         "accountId":"MMF046094001",
         "fundName":"UNITED CAPITAL MONEY MARKET FUND"
      },
      {
         "customerId":"046094",
         "coreSystem":"symplusAM",
         "accountId":"SIS046094001",
         "fundName":"UNITED CAPITAL STAFF INVESTMENT SCHEME"
      },
      {
         "customerId":"046094",
         "coreSystem":"symplusAM",
         "accountId":"EUROB046094001",
         "fundName":"UNITED CAPITAL NIGERIAN EUROBOND FUND "
      }
  ]
    }
  }
};
</script>

<style>
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

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

Is there a way to pass a c struct pointer into javascript using ffi?

I need help passing a pointer to a struct to a method in nodejs using ffi. I am encountering an error where the type of the JavaScript struct I created cannot be determined. How can I resolve this issue? Previously, I was able to successfully implement si ...

Preventing duplicate values in arrays using PDO

I am currently working on retrieving currency ids from a database using the following code: $arr = []; $currency_codes = array("USD", "RUB"); $currency_codes_in = implode(',', array_fill(0, count($currency_codes), '?')); $query = "SEL ...

What sets apart v-model from :model-value?

I'm curious because I have trouble grasping the distinction between v-model and :model-value. According to the information in the documentation: v-model is used on a native element: <input v-model="searchText"/> However, when used on ...

Having difficulty configuring unique paths for multiple APIs using Socket.IO, ExpressJS, and Nginx

I am currently working on setting up multiple APIs on a single VPS and serving them through Nginx. My goal is to have all of them organized in separate sub-locations, as shown in the example below: For Express remote paths: [myhost].com/apps/app1/api [myh ...

Transferring a Variable from Arduino to JavaScript

Is there a simple way to pass an Arduino variable as a JS variable? Let's say we have an integer Arduino variable called sensorData: int sensorData = analogRead(sensorPin); How can we transfer this value to a JavaScript variable? client.println(&quo ...

Troubleshooting PHP webpage with dysfunctional Python AJAX functionality

I have been working on developing a website that integrates with a python script to control GPIO pins on my Raspberry Pi. Unfortunately, I've encountered some issues with the code and need some assistance in troubleshooting. Could someone please revi ...

Integrate actual credentials into S3Client using redux async thunk

My S3-like react application with redux is powered by AWS SDK v3 for JS. The client initialization in my auth.js file looks like this: auth.js export const s3Client = new S3Client({ region: 'default', credentials: { accessKeyId: 'te ...

Please ensure that the form is only submitted when at least one checkbox is selected by utilizing JavaScript

When I visit the following form: Upon filling out the details and clicking submit, if I forget to check a checkbox, a prompt appears stating "please select any one checkbox" with an 'ok' button. After clicking 'ok', the form is then su ...

Unable to replicate the functionality of the tab key using jQuery for the enter key

How can I focus on the first input ('Qtd on the table') after pressing enter on the 'Buscar' input? I've tried various solutions like $(this).nextAll('input').first().focus(); $(this).next('input:text').focus ...

Using React.js with a PHP backend to create an API ecosystem for

Creating an admin panel for a website with CRUD operations has been quite the journey. I began by setting up API endpoints and hosting them on a subdomain. Fetching data from these endpoints was successful for displaying all contacts (GET), individual cont ...

Send image data in base64 format to server using AJAX to save

My goal is to store a base64 image on a php server using the webcam-easy library (https://github.com/bensonruan/webcam-easy). I added a button to the index.html file of the demo: <button id="upload" onClick="postData()" style=" ...

Guide to setting up a custom js file in Laravel admin template

Currently working with Laravel 5.8 and utilizing the laravel-admin Template for administrative purposes. There are times when I require custom JavaScript and CSS files specifically for certain admin controllers. How can I include these JS and CSS in lara ...

Turn off Babel's strict mode when transpiling JavaScript files

Currently, I am facing an issue while trying to transpile a set of JavaScript files using Babel. Since Babel operates in strict mode by default, it triggers a syntax error whenever there is a conflict like the use of the delete keyword. The solution I am s ...

VueJS is unable to access an array

Unable to access an array in Vue.js. console.log(this.ref_number_response[0]); When I try to access the array, it shows undefined. I'm puzzled by this... data(){ return{ ref_number_response: [], } }, methods:{ che ...

Creating a TypeScript generic type for the "pick" function to define the types of values in the resulting object

I am facing an issue while writing the type for the pick function. Everything works smoothly when picking only one key or multiple keys with values of the same type. However, if I attempt to pick a few keys and their values are of different types, I encoun ...

Arranging arrays of various types in typescript

I need help sorting parameters in my TypeScript model. Here is a snippet of my model: export class DataModel { ID: String point1: Point point2 : Point point3: Point AnotherPoint1: AnotherPoint[] AnotherPoint2: AnotherPoint[] AnotherPoi ...

Trigger jQuery Waypoints Only Once

Utilizing , I am seeking to trigger a specific action when the user scrolls down to the section marked with the class div1. However, the action should only occur once and not repeatedly each time the user reaches that point. — just once $('.div1&ap ...

What is the best way to set the v-model property to an object that is constantly changing

I'm in the process of creating a dynamic form that allows users to add additional fields by simply clicking on a button labeled "adicionar condição." The concept is similar to what can be seen in the screenshot below: https://i.stack.imgur.com/Mpmr6 ...

After a period of 10 minutes with no activity, proceed to the next page

I am in the process of developing a custom local website that will be displayed on a large touch screen at my current workplace. Only one user can interact with it at a time. My client has requested a screensaver feature to appear after 10 minutes of no i ...

Issue with Bootstrap Carousel Interval Setting not Functioning as Expected

I recently added Twitter Bootstrap-Carousel to a website with the intention of using it to navigate through different sections of a module. However, I'm encountering an issue where setting the interval to false does not work as expected. When I set an ...