How to easily toggle all checkboxes within a Vue.js checkbox group

I'm struggling with manipulating an Array of checkboxes that are grouped into parent and child elements. I need to automatically check all child checkboxes when the parent is checked, uncheck them if the parent is unchecked, and update their states in the Array accordingly. However, this task is way over my head as I am new to Vue.

To illustrate my issue, I created a Codepen here. Unfortunately, I am unable to change the structure of the Array since it's a JSON response from the server.

Could someone please guide me through this problem? Any help would be greatly appreciated. Thank you in advance!

Answer №1

When working on the template,

<input type="checkbox"
       :disabled="item.state.disabled" 
       :name="item.text" 
       :checked="item.state.selected" 
       @click="item.state.selected = !item.state.selected"
       @change="onChange(item, item.state.selected)">

Don't forget to include this method as well,

methods : {
    submitForm() {
        console.log(tree);
    },
    onChange(item, state){
        for(let child of item.children){
            child.state.selected = state
        }
    }
}

Check out the updated pen.

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

Unusual class exhibiting peculiar async/await patterns

Node 7.9.0 The situation goes like this: class TestClass { constructor() { const x = await this.asyncFunc() console.log(x) } async asyncFunc() { return new Promise((accept) => { setTimeout(() => accept("done"), 1000) }) ...

The Next.js middleware, specifically NextRequest.nextUrl.locale, will return an empty string once it is deployed

Encountering a bug in the next-js middleware The middleware function is returning a NextRequest param According to the documentation from Next.js: The NextRequest object is an extension of the native Request interface, with the following added metho ...

Display a collection of Mongoose objects in a React component

In my development stack, I rely on node js + React. The data I work with comes from mongoose and typically follows this format: { "_id": "61b711721ad6657fd07ed8ae", "url": "/esports/match/natus-vincere-vs-team-liquid- ...

Are there any extensions in VS Code that can identify all files that are importing the current file?

class ButtonNoclickTag is exported default {...} I am curious to find out which files have imported this ButtonNoClickTag component through vscode ...

Using JavaScript to place image data on the canvas in an overlay fashion

I recently wrote the code below to generate a rectangle on a canvas: <!DOCTYPE html> <html> <body> <canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;"> Your browser does not support the HTML5 canv ...

Cease the ongoing Ajax request and switch to a new Ajax call immediately

Within this code snippet, I am capturing user input for typing and then searching it in a database. However, with each character entered by the user, a new AJAX request is triggered without canceling the previous one. My objective is to have the search fu ...

An error occurred while trying to retrieve a resource from the bower_components directory using Vue.js CLI

I encountered an error in my project when trying to reference CSS and JS files. Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:8080/bower_components/bootstrap/dist/css/bootstrap.min.css This is how my file ...

Remove the underline from links in gatsbyjs

When comparing the links on (check source code https://github.com/gatsbyjs/gatsby/tree/master/examples/using-remark), they appear without an underline. However, on my blog (source code here: https://github.com/YikSanChan/yiksanchan.com), all links are un ...

Securely transmit ID values through ajax calls

Picture this: I have a website where users' profile pages are accessed through addresses like the following: http://www.samplewebsite.com/profile.php?p=123 Now, I want to be able to block or perform another action on a user when I click a button. To ...

Tips for inserting a hyperlink on every row in Vuetables using VUE.JS

Trying to implement a link structure within each row in VUEJS Vuetables has been challenging for me. Despite my research on components and slots, I am struggling to add a link with the desired structure as shown below: <td class="text-center"> <a ...

Setting a cookie in a browser using an AJAX response: A step-by-step guide

When utilizing a Javascript function with jQuery to send a POST request to a web service, the response from the web server includes a header "Set-Cookie: name=value; domain=api.mydomain.com; path=/", along with a JSON body. However, despite this expected ...

What could be causing the issue with the .toLocaleTimeString method not properly converting time zones?

I have been attempting to convert timezones based on the current time, but I haven't had success. I tried switching from using date.toLocaleTimeString to date.toLocaleString, but it didn't work. I also tried changing the timezone from America/Den ...

Warning: Knex was unable to acquire a connection due to a timeout, resulting in an UnhandledPromiseRejectionWarning

I'm having trouble connecting my Telegram bot to the database using knex. I am working with MySQL, and I have already created the database and tables which are visible on the /phpMyAdmin page. The credentials used for accessing the database in my code ...

Configuring routers for my node.js application

I've been facing several challenges with setting up the routes for my node.js application. Below is a snippet of my app.js file where I call the route. const express = require("express"); const bodyParser = require("body-parser"); const app = exp ...

Guide on incorporating Bootstrap JS into HTML5 reusable web elements

RESOLVED: the solution is in a comment TL;DR: Issues triggering Bootstrap's JS, likely due to incorrect import of JS scripts I've been working on integrating Bootstrap with my custom reusable web components across all pages. Specifically, I&apo ...

Incorporating VueJS with a Dynamic PHP Variable

I am working on binding an HTML element that contains a PHP echoed string so I can leverage it with VueJS. The goal is to switch between GBP and USD based on certain php/mysql database queries (USD being the default value). Let's take a look at what I ...

Enable the button if at least one checkbox has been selected

I've written some code similar to this: $('input[type=checkbox]').click(function(event) { $('.chuis').each(function() { if(this.checked) { $('#delete_all_vm').prop("disabled",false); } ...

My code written using Visual Studio Code is not displaying properly when I view it in my browser

I have been following along with a tutorial series that can be found at this link. This link will take you to the third video in the series, but I have also followed and programmed alongside the first and second videos. After installing Visual Studio Code ...

Transferring data between Javascript and PHP with AJAX and JQuery

I'm currently working on a basic web page that involves sending data from an HTML page to a PHP script and receiving some data back. My approach involves using AJAX, but for some reason, the PHP script doesn't seem to execute at all. Here's ...

Getting started with `sessionStorage` in a React application

Currently, I am attempting to save an item in sessionStorage prior to rendering. The code snippet I have looks like this: componentWillMount() { sessionStorage.setItem("isUserLogged", false); } However, I encountered an error stating th ...