checkbox appear based on vue condition

I have checkboxes on my list that are always checked, but I only want them to be checked if the associated object's property "include" is set to true.


Currently, all the checkboxes are checked by default, and when I click on them, they uncheck and exclude the students. I need to have the boxes unchecked unless I manually check them.

I don't have a "checked" attribute set on the template, so I'm not sure why they are checked by default. I'm hoping someone can help me identify my mistake.

Here is the data for my absent students:

absentStudents: [{
                    "id": 207,
                    "first_name": "Gabriel De Manuel",
                    "include": false,
                    "avatar": null,
                    "group_id": 24,
                    "full_name": ", Gabriel De Manuel",
                    "exclude": false ,
                    "isGrouped": false, 
                }, {
                    "id": 208,
                    "first_name": "Francisco",
                    "include": false,
                    "avatar": null,
                    "group_id": 24,
                    "full_name": ", Francisco",
                    "exclude": false, 
                    "isGrouped": false, 
                }, {
                    "id": 209,
                    "first_name": "Rosa",
                    "include": false,
                    "avatar": null,
                    "group_id": 24,
                    "full_name": ", Rosa",
                    "exclude": false,
                    "isGrouped": false,  
                }],
            excludeAbsent: false,

//my v-model is created by the following function
 created() {
                this.absentStudentsSelected = this.absentStudents.map(x => x.id);
            },

I have displayed these checkboxes for my list

 <ul>
                    <li v-for="absentStudent in absentStudents" class="list-unstyled">
                        <input type="checkbox" @click="check($event)" v-model="absentStudentsSelected" :value="absentStudent.id">
                        {{ absentStudent.first_name }}
                    </li>
                </ul>

Check the boxes for each student only if the "excludeAbsent" property is set to true

check: function(e){  
                    if(this.excludeAbsent === true){ //if we want to include absent students

                    for(var i = 0; i< this.absentStudents.length; i++){
                        if(e.target. value == this.absentStudents[i].id){

                                this.absentStudents[i].include = true 
                            }else{
                                this.absentStudents[i].include = false 
                            }
                        }
                    }

Answer №1

absentStudentsSelected needs to be set as an empty array within your data option:

let app = new Vue({
  el: "#app",
  data() {
    return {
      absentStudents: [{
        "id": 207,
        "first_name": "Gabriel De Manuel",
        "include": false,
        "avatar": null,
        "group_id": 24,
        "full_name": ", Gabriel De Manuel",
        "exclude": false,
        "isGrouped": false,
      }, {
        "id": 208,
        "first_name": "Francisco",
        "include": false,
        "avatar": null,
        "group_id": 24,
        "full_name": ", Francisco",
        "exclude": false,
        "isGrouped": false,
      }, {
        "id": 209,
        "first_name": "Rosa",
        "include": false,
        "avatar": null,
        "group_id": 24,
        "full_name": ", Rosa",
        "exclude": false,
        "isGrouped": false,
      }],
      excludeAbsent: false,
      absentStudentsSelected: []
    }
  },
  methods: {
    check: function(e) {
      if (this.excludeAbsent === true) {
        for (var i = 0; i < this.absentStudents.length; i++) {
          if (e.target.value == this.absentStudents[i].id) {
            this.absentStudents[i].include = true
          } else {
            this.absentStudents[i].include = false
          }
        }
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <ul>
    <li v-for="absentStudent in absentStudents" class="list-unstyled">
      <input type="checkbox" @click="check($event)" v-model="absentStudentsSelected" :value="absentStudent.id"> {{ absentStudent.first_name }}
    </li>
  </ul>
  </div>

Answer №2

Properly utilize the checked attributes for the input elements as per the latest WhatWG Html standard guidelines. Vue may not have a built-in way to include attributes conditionally, so resort to a slightly redundant approach of conditionally rendering the element:

<ul>
    <li v-for="absentStudent in absentStudents" class="list-unstyled">
        <input
            v-if="excludeAbsent && absentStudent.include"
            type="checkbox"
            @click="check($event)"
            v-model="absentStudentsSelected"
            :value="absentStudent.id"
            checked
        />
        <input
            v-else
            type="checkbox"
            @click="check($event)"
            v-model="absentStudentsSelected"
            :value="absentStudent.id"
        />
        {{ absentStudent.first_name }}
    </li>
</ul>

Consider adjusting the condition in the v-if directive for checking or not checking the checkboxes. Manipulating the DOM directly in the click handler is an option, but it goes against the declarative nature of frameworks like Vue.

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

The checkboxes seem to be malfunctioning following an ajax request

I've been attempting to utilize ajax to load data, but for some reason the checkboxes aren't functioning. Below is the HTML I'm trying to load via ajax: <div class="mt-checkbox-list" > <?php foreach($product_offerings as $row){ $c ...

JS Unable to get scrollIntoView function to work with mousewheel event

I have been working with the script provided above. It correctly displays the id in the browser console, but unfortunately, it is not triggering the scrolling function as expected. var divID = null; var up = null; var down = null; function div(x) { s ...

The Powerful Duo: JavaScript and Regex

Having some issues with the code snippet below, I know there's an error in my code but I can't seem to figure out what it is (tried enclosing the code in quotes but that didn't work...) var Regex = require('regex') var regex = new ...

Is there a way to prevent a page from automatically redirecting to another page without relying on user action or using the StopPropagation and window.onbeforeunload event?

function confirmExit(e) { var f = FormChanges(); //checking if the page has been modified if (f.length > 0){ if (submitForm == false) { if(!e) var e = window.event; e.cancelBubble = true; e.returnValue = "You ...

Ways to identify when a chemical reaction has taken place?

I have developed a Discord bot that interacts with an API related to a game server panel. The bot has tasks to start, restart, stop, and kill the server. I want to enable end users to trigger these tasks by reacting to a specific embed posted by the bot. ...

Combining data from various JSON files to create dynamic charts with Highcharts

At this moment, my Highchart code is set up in a way where I want to replace the static data-series values within the HTML file with information loaded from a JSON file. The current code appears as follows: <!doctype html> <script type="text/jav ...

The MUI persistent drawer navigation bar becomes dysfunctional when accessing a specific route

Exploring the MUI library for the first time, I successfully created a navigation bar that functions properly for one route (Dashboard). However, when attempting to implement it on the candidate route, it collapses as shown in this Screengrab of collapsed ...

Converting JSON DateTime objects to local time in JQuery without considering timezones

I am struggling with parsing a JSON DateTime object using moment.js. Despite trying various methods recommended on Stackoverflow, nothing seems to work in my case. In my application, I save DateTime values in UTC format and when displaying them, I need to ...

Change locale in Vue with Vue-i18n

Consider the following code: <ul> <li v-for="(lang, i) in $i18n.availableLocales" :key="`Lang${i}`" :value="lang"> <a href="#" @click="setLocale('what should be placed here?')" ...

How come the link function of my directive isn't being triggered?

I'm encountering a strange issue with this directive: hpDsat.directive('ngElementReady', [function() { return { restrict: "A", link: function($scope, $element, $attributes) { // put watche ...

Using a local API in conjunction with a Vue app hosted on a separate port: a guide

I am currently assisting with setting up a Django + Vue application for someone, and we are facing an issue regarding how to enable hot-reloading in the Vue app while also being able to communicate with the local Django server. In the production environme ...

What are the steps to start up a NodeJS API using an Angular app.js file?

Currently, I am following various online tutorials to develop a web application using the MEAN stack and utilizing a RESTful API. I have encountered some challenges in integrating both the API server and Angular routes. In my project, I have a server.js f ...

Implement the usage of plainToClass within the constructor function

I have a dilemma with my constructor that assigns properties to the instance: class BaseModel { constructor (args = {}) { for (let key in args) { this[key] = args[key] } } } class User extends BaseModel { name: str ...

Viewer model aggregation - coordinating problem

In the Viewer, I am dynamically aggregating models from multiple BIM files. The process involves initializing the viewer and then using LoadDocument and LoadModel for each model chosen by the user. These models are primarily NVC files (the ones I used for ...

Update the variable obtained from the user input and insert it into a new container depending on the input value

In reference to my previous inquiries, I refrain from adding more details to avoid confusion since it already received numerous responses. While I can successfully retrieve input from a text field with the ID 'test' and display it in the 'r ...

Adjust the position of the footer up or down based on changes in page content height

If I have jQuery at my disposal, how can I achieve the following task? There is a div on the page with dynamic content and no fixed height. The height of this div changes as users type and content appears or disappears accordingly. Although everything is ...

Is there a way to determine if a submit button has been clicked in order to prevent my function from executing?

I'm currently developing a platform for uploading images. Once a user uploads an image successfully, it gets saved in 4 different sizes within separate folders. They are then redirected to the same page with new content, where they can proceed to crop ...

Having issues with "return false" not functioning properly in jQuery ajax calls

I have been developing a registration form using jQuery ajax. Below is the code snippet I am working with: function validateData() { var email = jQuery("#email").val(); var username = jQuery("#username").val(); var emailReg = /^([\w-&bsol ...

Having issues with InstaFeed (search) feature and jQuery Mobile

As a new developer, I am working on my first JQM site. However, I am facing an issue with my search input form where the instafeed photos do not show up until after a manual page refresh following submission. Despite numerous attempts, I cannot seem to res ...

Update database upon drag-and-drop using jQuery

I have a dataset (shown below) that undergoes sorting by 'section'. Each item is placed into a UL based on its section when the page loads. My goal is to automatically update the section in the database when a user drags an item to a different s ...