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

Reactstrap: Is it necessary to enclose adjacent JSX elements within a wrapping tag?

While working on my React course project, I encountered an issue with my faux shopping website. The error message that keeps popping up is: Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...& ...

Tips for stopping execution in Discord.js if the user no longer exists?

I'm currently working on a discord bot and encountered a minor issue. I am using "messageReactionRemove" and "messageReactionAdd" to manage certain roles by removing or adding them, but the problem arises when a user leaves the server. When this happe ...

Handsontable: A guide on adding up row values

I have a dynamic number of columns fetched from the database, making it impossible to predict in advance. However, the number of rows remains constant. Here is an illustration: var data = [ ['', 'Tesla', 'Nissan', & ...

Creating a row of aligned card components in React

Recently, I began learning React and successfully created a card component using Material UI. However, this time around, I'm attempting to create it using axios and map() methods. I expected the cards to be displayed in the same row horizontally, not ...

retrieve data types from an array of object values

I am looking to extract types from an array of objects. const names = [ { name: 'Bob' }, { name: 'Jane' }, { name: 'John' }, { name: 'Mike' }, ] The desired result should resemble thi ...

Using the Table-multiple-sort feature in boostrap-table is not functioning properly when there are multiple tables present on a single page

I have implemented bootstrap-table along with the extension table-multiple-sort. The issue I am facing is when I include two tables on a single page (with the second table within a modal window), the multisort feature does not seem to work on the second ta ...

Emphasizes the P tag by incorporating forward and backward navigation options

My goal is to enable users to navigate up and down a list by pressing the up and down arrow keys. For example, if "roma" is currently highlighted, I want it to change to "milan" when the user presses the down arrow key. Here is the HTML code I am working w ...

Validating usernames using Jquery's remote method检verifying the username

Struggling with the validation plugin and Laravel 4.2. I've been attempting to use ajax to check the username, but it's not functioning as expected. No matter if the username exists or not, it always appears available. Another problem arises whe ...

What is the process for implementing a fallback image in Material UI?

Hey there! I'm currently looking to customize the fallback image of a Material UI Avatar with my own original image. Does anyone have any tips on how I can achieve this? const fallbackImage = "../../fallback/img.png" const AvatarWithBadge = ...

The function is returning an undefined value in node.js due to the boolean condition

I have two functions. The first one is in auth.js, and it looks like this: const adminCheck = (req, res) => { console.log(“one”) UtilRole.roleCheck(req, res, ‘ADMIN’, (response) => { if(response) { return true ...

Integrate the dateFilter function into a service within an AngularJS application

Is there a way to include filters in AngularJs services? I've been experimenting app.factory('educationService', [function($rootScope, $filter) { // ..... Some code // What I want console.log(dateFilter(new Date(), 'yyyy ...

Error: The command "vue" is not recognized

I am encountering an issue while trying to set up vue-cli using npm. Each time I check the version, I receive the error message -bash : vue: command not found. Despite my efforts which include uninstalling and reinstalling, as well as referring to resourc ...

Setting the default date in angular-bootstrap-datetimepicker: a step-by-step guide

I am currently utilizing the angular-bootstrap-datetimepicker module for allowing users to choose a date and time. How can I set a default date and time when the view initially renders? Is there an attribute available that allows us to assign a boolean val ...

Encountering the "Local resource can't be loaded" error when attempting to link a MediaSource object as the content for an HTML5 video tag

I'm attempting to make this specific example function properly. Everything runs smoothly when I click the link, but I encounter an error when trying to download the HTML file onto my local machine and repeat the process. An error message pops up sayi ...

Updating all the direct components within the corresponding category with jQuery

Here is the HTML content I am working with: <li class="info"> info<li> <li class="other"> info<li> <li class="other"> info<li> <li class="Error"> error<li> <li class="other"> error<li> < ...

Embed an external website within a div element

Is there a way to embed an entire external website onto another site, without scroll bars or borders? I attempted this method but the entire page did not load, and there were still scroll bars and borders present. <!DOCTYPE HTML> <html> <b ...

Using AJAX with the GET method, send a form submission to retrieve a response using XMLHTTPRequest

I am working on a form where users can select values from two dropdown menus. The options in the dropdowns are populated dynamically from a JavaScript file, which contains a list of exchange rates. I have written the code to calculate and display the resul ...

The Material UI Drawer is fading into the background instead of smoothly sliding into view

Seeking guidance as a novice in SD, I am dedicating my free time to honing my skills. Any advice is appreciated, but please explain it as if I were a child. My current endeavor involves making the Drawer Component feature functional and customizing it to s ...

I'm currently working on incorporating an edit feature into the create form by utilizing server actions in the latest version of Next.js, version 14

The issue arises when the create form's type (id) parameter is null, which does not align with prisma's (edit info). export function AboutForm({ id }: { id: number }) { const router = useRouter(); const [err, setErr] = useState("&qu ...

Creating complex concave shapes using Three.js from a point cloud

Currently facing a challenge in dynamically creating shapes in three.js from a point cloud. While ConvexGeometry works well for convex shapes, it becomes complex when dealing with concave shapes. The process involves drawing a line on the 2D plane (red li ...