Enable checkbox selection on Vue.js table rows with a simple click

Having trouble making a list item clickable? Need the checkbox within the list item to be enabled or disabled on click, but it's not behaving as expected?

Here is an example:

var app = new Vue({
  el: '#app',
  data: {
    showNav: false,
    categories: [{name: 'test' }]
  },
  mounted() {

    this.categories.forEach((category) => {
      category.active = true;
    });
  }
})
<div id="app">
  <nav class="navbar-dropdown w-full">
      <ul class="list-reset">
          <li class="flex justify-between items-center hover:bg-grey hover:text-white text-grey uppercase cursor-pointer p-3" v-for="category in categories" @click="category.active = !category.active">
              {{ category.name }}
              <input type="checkbox" class="shadow" v-model="category.active" @click="category.active = !category.active"/>
          </li>
      </ul>
  </nav>
</div>


<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0573706045372b302b3433">[email protected]</a>/dist/vue.js"></script>
<link href="https://cdn.jsdelivr.net/npm/tailwindcss/dist/tailwind.min.css" rel="stylesheet"/>

While changing:

categories: [{name: 'test' }]

To:

categories: [{name: 'test', active: true }]

gets it working. But if your application fetches the data with an ajax and doesn't include the active property for category objects, you may face issues like:

this.categories.forEach((category) => {
      category.active = true;
    });

What could be done to address this problem?

Answer №1

As someone pointed out in the comments, there seems to be a problem with how you are defining the property for a category. While it may be difficult to pinpoint exactly why this approach is causing issues, here is an alternative way to achieve the same result:

const app = new Vue({
  el: '#app',
  data: {
    showNav: false,
    categories: [{
      name: 'test'
    }],
  },
  mounted() {
    this.categories = this.categories.map((category) => {
      return {
        name: 'test',
        active: true,
      };
    });
  },
});
<div id="app">
  <ul class="list-reset">
    <li class="flex justify-between items-center hover:bg-grey hover:text-white text-grey uppercase cursor-pointer p-3" v-for="category in categories" @click="category.active = !category.active">
      {{ category.name }}
      <input type="checkbox" class="shadow" v-model="category.active" @click="category.active = !category.active" />
    </li>
  </ul>
</div>


<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

I am open to any additional insights or explanations as to why the original poster may be experiencing this issue.

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

Trim the final digits from the arrays

I have an array that contains various strings: var arr = ['1234','23C','456','356778', '56'] My goal is to filter out array elements that are less than 3 characters or more than 4 characters. The resultin ...

Issue with capturing mouse position in canvas when hovering over <h1> element above it

I am working on a project using React Three Fiber to animate a 3D model that follows the mouse cursor. However, I have noticed that when the mouse hovers over some divs or headings on top of the canvas element, the animation freezes and becomes choppy unti ...

Typescript's Nested Type Assignments

Simply put, I'm making an API call and receiving the following data: { getUserInfo: { country: 'DE', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3c48594f487c59445d514c5059125f5351">[e ...

"Retrieving Data Using jQuery's .ajax Method in Visual Basic

<WebMethod()> Public Shared Function gtet() As String ... Dim GET = uClass.GetSets(dbuser, dbparam1) ... End Function and $(document).ready(function () { data = { }; var jsondata = $.toJSON(data); $.ajax({ type: "GET ...

Unable to populate an HTML table with JSON data

Can you assist me in populating a table using data from a JSON response? [ { "id": 1, "firstName": "James", "nickNames": [ {} ] }, { "id": 2, "firstName": "Linda", "nickNames": [ { "id": 2, "na ...

AngularJS fails to trigger window scroll event

Although I have come across similar inquiries regarding this issue, none of the solutions have proven to be effective for me. Currently, I am working with AngularJS and I am attempting to detect the scroll event. Despite trying numerous variations to capt ...

Bootstrap 4 Collapse - Ensuring that collapsed elements remain open when expanding other accordions

Can someone help me figure out how to keep an element open when another one is opened? Here is an example: https://getbootstrap.com/docs/4.0/components/collapse/ <div id="exampleAccordion" data-children=".item"> <div class="item"> & ...

js - stop form submission

After clicking on a button with type="submit", the front-end validation starts, but I also need to perform server-side validation using Ajax. This includes checking if the name is already being used by another person. The issue arises when switching the b ...

Vue not displaying in Chrome - The div has been replaced by <!---->

I'm in the process of deploying a simple Vue application on Cloud Foundry. Below is the code for the single-page Vue application: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>title</title> ...

What is the best way to switch the visibility of a div on click from another div?

My goal is to make a div toggle visible or hidden when another div is clicked. The only connection between the two divs is that they are both nested within the same parent div. There's a DIV element with the class of "comment" which contains a DIV ele ...

The read more button is not functioning properly when used in conjunction with the <br>

Can someone help me debug an issue I'm facing with my code? I have created an HTML tab that contains multiple DOM elements, each with a "Read More" button. Everything works fine when it's just plain text, but as soon as I add tags within the p ...

Steps for generating an observable that mirrors the structure of an observable array

I am in the process of creating an observable array using JSON data retrieved from the server. var ViewModel = function (data) { var self = this; self.list = ko.observableArray(data); self.selected = ko.observable(); } ...

Delete an item from an array when a dropdown selection is made

When dealing with Angular 8, I encountered a logic issue. There are two drop-down menus: First Drop-down The options in the first menu are populated from an array of objects Example Code, ts: {rs_id: "a5f100d5-bc88-4456-b507-1161575f8819", ...

The Workbench has "Rejected the setting of an insecure header 'content-length'"

While working on implementing a simple xhr abstraction, I encountered a warning when trying to set the headers for a POST request. Strangely, I noticed that the issue might be related to setting the headers in a separate JavaScript file. This is because wh ...

The ngIf statement in the template isn't functioning properly after a refresh; instead, it is causing a redirection to the homepage

I've been developing with Angular 7, trying to display a <div> ... </div> based on multiple values that I declared as : Boolean = false; in the .ts file. These values are updated in ngOnInit, but for some reason, the page keeps redirecting ...

Retrieve an item from the Ionic Firebase database

My current challenge is retrieving data from the Firebase database. user-service.ts getProfile(){ try {; return this.afDatabse.object(`profile/${this.afAuth.auth.currentUser.uid}`); } catch (e) { console.log(e); } } c ...

Close session when browser/tab is exited

After extensive searching online, I have been unable to find a satisfactory solution for ending a session when a browser or tab is closed without requiring the user to log off. I have attempted numerous JavaScript codes that I came across, but none of the ...

What are the possibilities of combining Laravel Voyager and Vue SPA in my projects?

Can anyone provide some assistance with an issue I am facing in my Laravel and Vue SPA project? I am using (Vue SPA) along with Laravel Voyager for the admin panel. The problem arises when I try to access the admin panel using the path: /admin, as it doe ...

Encasing common functions within (function($){ }(jQuery) can help to modularize and prevent

As I was creating a global JavaScript function and made some errors along the way, I finally got it to work after doing some research. However, while searching, I came across an example using (function($){ code here }(jQuery); My question is, what exact ...

Building a dynamic form in Angular that includes dynamic event binding and dynamic function execution

Hey there, I'm just starting out with angular and I'm looking to create a form that can render using JSON data which also includes events and functions. Here's the setup: <div *ngFor="let form of forms; index as i "> <div ...