Linking a group of child checkboxes to a single parent

Is there a way to link multiple checkboxes from various child elements to one parent element (e.g. using a model)?

Imagine that each child component includes something like:

<input
  type="checkbox"
  :id="'ticket-'+id"
  :checked="checked"
/>

Now, can we have a parent property called selected that would gather the ids of all checked checkboxes from the children in an array?

{
  selected: [
    5,
    8
  ]
}

The closest solution I found is this. However, I don't want to track unchecked instances in my case.

Answer №1

To handle the checkbox change events on the parent and update the data model, you can create a method.

Take a look at the code snippet below for an example of how this can be implemented: (View in full screen for better visibility)

new Vue({
  el: "#app",
  data: {
    list: [
    { id: 1, label: 'Check 1'},
    { id: 2, label: 'Check 2'},
    { id: 3, label: 'Check 3'},
    { id: 4, label: 'Check 4'},
    ],
    selected: []
  },
  methods: {
    handleChange: function(ev) {
      let id = ev.target.id;
        if (ev.target.checked) {
        if (!this.selected.includes(id)) {
            this.selected.push(id);
        }
      } else {
        this.selected = this.selected.filter(function (item) {
            return item !== id;
        });
      }
      
      console.log('Updated: ', this.selected);
    }
  }
})
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

li {
  margin: 8px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>


<div id="app">
  <ol @change="handleChange">
    <li v-for="check in list">
      <label>
        <input type="checkbox" :id="check.id" />
        <span>{{check.label}}</span>
      </label>
    </li>
  </ol>
</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

Troubleshooting the defects in the string-to-json module functionality

I am dealing with string data var str2json = require('string-to-json'); var information={ "GTIN" : "GTIN 3", "Target Market" : "Target Market 3", "Global Location Provider Name(GLN) 3" : "Global Locati ...

Tips for moving a polygon while dragging a marker within its boundaries

Currently, I have a map displaying polygons and markers, accompanied by a sidebar featuring tool buttons (similar to the setup showcased in this demo: ). Each marker on my map is connected to the respective polygon stored in my database. When I utilize the ...

What is the reason for the index type being defined twice?

Here is an example from the official TypeScript documentation: class Animal { name: string; } class Dog extends Animal { breed: string; } // Error: indexing with a 'string' will sometimes get you a Dog! interface NotOkay { [x: numbe ...

Creating a method that can adopt the return type of the nested function?

I have a function that takes in a callback and returns the value obtained using the useSelector hook from the react-redux library. Is there a way to utilize the return type of useSelector within my wrapper function? import { shallowEqual, useSelector } f ...

Troubleshooting the Checkbox Oncheck Functionality

Before checking out the following code snippet, I have a requirement. Whenever a specific checkbox (identified by id cfc1) is clicked, it should not show as checked. I have implemented the onCheck function for this purpose, but I'm struggling to fig ...

What are the steps for launching a node.js application within vert.x?

I am completely new to vert.x and I am currently exploring the possibility of migrating an existing nodejs application to vert.x. At this point, I have followed the steps outlined in to install vert.x using npm. While I was able to run a simple hello-worl ...

What steps should I take to incorporate a timer into my bot similar to the timer used by other giveaway bots

I am looking to add a timer to my bot giveaway embed message that continues to update itself even when the bot is offline, without showing that the message was edited. Here's what I currently have in my embed: const embed = new MessageEmbed(); ...

The type 'MouseEvent<HTMLButtonElement, MouseEvent>' cannot be matched with the type 'boolean'

Just starting out with TS and running into a problem that TS is pointing out to me. Error: Type '(x: boolean) => void' is not compatible with type '(e: MouseEvent<HTMLButtonElement, MouseEvent>) => void'. Parameters ' ...

Issue with handling 'this' in submit function in Sencha touch/JavaScript not resolved

I am currently working on developing a form using Sencha Touch that is designed to allow users to enter text and conduct a job search on a website. While most of the functionality is in place, including the reset button, I encounter an error when attemptin ...

How to format a Date object as yyyy-MM-dd when serializing to JSON in Angular?

I have a situation where I need to display an object's 'birthDate' property in the format DD/MM/YYYY on screen. The data is stored in the database as YYYY-MM-DD, which is a string type. I am currently using bootstrap bsDatePicker for this ta ...

What is the best way to refresh NGRX data?

There are two models in a one-to-many relationship: export interface GroupModel { id: number; name: string; userIds?: number[]; } export interface UserModel { id: number; name: string; groupId?: number; } An issue arises when updating either m ...

"Utilize Vue i18n to properly display currency amounts in USD

Whenever I present my currency as USD, it always shows up like this: USD$500.00. I am attempting to eliminate the USD prefix from the beginning. Below is my numberFormats configuration: numberFormats: { 'en': { currency: { ...

What are some ways I can extract a value using Vue.js?

I've been working with Vue for a few days and have run into an issue. I am using jQuery AJAX to load text content in the template, but I need to truncate the title and description with ellipsis. Here is the method I wrote: methods:{ t ...

How can I utilize a variable in a v-for loop as a label for a q-btn in Vue.js?

I have a list: myList = [1, 2, 3, 4, 5, 6, 7, 8, 9] I'd like to generate buttons using this list where the label corresponds to the number: <q-btn v-for="number in myList" v-bind:key="number" color="primary" label=&q ...

Collaborating and monitoring data between controllers

A unique challenge has arisen as we implement a tree-style navigation element that must communicate with other directives/controllers. The main objectives are: Keep track of the current selection, Detect when the row selection changes. The task at hand ...

Is the "mocha" command line tool requires quotation marks for specifying test files?

Here are some examples of npm scripts: "scripts": { "test": "mocha tools/testSetup.js src/**/*.spec.js" } "scripts": { "test": "mocha tools/testSetup.js 'src/**/*.spec.js'" } "scripts": { "test": "mocha tools/testSetup.js \"src/**/* ...

Ways to stop grabber applications from identifying and saving mp3 files directly from the web browser

I am in the process of creating a music streaming platform that caters to both premium and free users. https://i.sstatic.net/J9gok.jpg As shown in the screenshot above, users with grabber apps installed on their browsers (such as IDM and other download a ...

Exploring TypeScript: TS2349 - The function you are trying to call is not callable. The type 'never' does not have any call signatures

Currently, I am delving into typescript and attempting to integrate it into an existing vue3-project. Here is the previous mixin-method: export const promises = { methods: { async process(...args): Promise<unknown> { return ...

Compilation of various route parameters

This route configuration example showcases how to extract parameters from a URL: URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby Route: /Chapter/:chapterId/Section/:sectionId Using this setup, we can obtain the following object: {chapt ...

Looping Angular Components are executed

I am currently developing an Angular application and encountering an issue with my navbar getting looped. The problem arises when I navigate to the /home route, causing the navbar.component.html components to duplicate and appear stacked on top of each oth ...