What could be causing the checkbox filter to malfunction in VueJS?

After spending a solid 8 hours attempting to make this work, I'm still struggling. My main goal is to display a loop that shows all items by default. Then, when a user selects a checkbox, it will filter out the items where they are set to false.

Here's my group of checkboxes and loop:

  <div class="container" id="clubs">
    <div class="filter">
        <label><input type="checkbox" v-model="selectedCategory" value="All" /> All</label>
        <label><input type="checkbox" v-model="selectedCategory" value="ClubParking" /> Parking</label>
        <label><input type="checkbox" v-model="selectedCategory" value="ClubToilets" /> Toilets</label>
        <label><input type="checkbox" v-model="selectedCategory" value="ClubFloodlights" /> Floodlights</label>
    </div>

    <ul class="clubs-list">
         <li v-for="club in filteredClubs">{{ club.clubName }}</li>
    </ul>
</div>

And here's the relevant code snippet from my application:

var vm = new Vue({
    el:  "#clubs",
    data: {
        clubs: [
            { clubName: "Club One", clubParking: true, clubToilets: false, clubFloodlights: true },
            { clubName: "Club Two", clubParking: true, clubToilets: false, clubFloodlights: false },
            { clubName: "Club Three", clubParking: false, clubToilets: true, clubFloodlights: true },
        ],
        selectedCategory: "All"
    },
    computed: {
        filteredClubs: function() {
            var vm = this;
            var category = vm.selectedCategory;

            if(category === "All") {
                return vm.clubs;
            } else {

               return vm.clubs.filter(function(club) {
                  return selectedFieldNames.every(fname=>club[fname])
                    const selectedFieldNames =  selectedCategory.map(category=>{
                        switch(category){
                           case 'Toilets':
                            return 'clubToilets';
                           case 'Parking':
                            return 'clubParking';
                           case 'Floodlights':
                            return 'clubFloodlights';
                        }
                    })

                });

            }
        }
    }
});

If you want to see a live example, I've created a Codepen. Your assistance would be greatly appreciated as I've been cooped up at home all day trying to crack this problem.

Answer №1

Made the necessary changes to your codepen based on the comments above: 1. Switched from using a "string" for selectedCategory to an "array" 2. Updated filtering logic to accommodate arrays

var vm = new Vue({
el:  "#clubs",
data: {
clubs: [
{ clubName: "Club One", clubParking: true, clubToilets: false, clubFloodlights: true },
{ clubName: "Club Two", clubParking: true, clubToilets: false, clubFloodlights: false },
{ clubName: "Club Three", clubParking: false, clubToilets: true, clubFloodlights: true },
],
selectedCategories: ["All"]
},
computed: {
filteredClubs: function() {
if (this.selectedCategories.includes('All')) {
return this.clubs;
} else {
        return this.clubs.filter(club => {
          return this.selectedCategories.some(category => club[category])
        })
}
}
}
});
.container {
padding: 20px;
width: 90%;
max-width: 400px;
margin: 0 auto;
}

label {
display: block;
line-height: 1.5em;
}

ul {
margin-left: 0;
padding-left: 0;
list-style: none;
}

li {
padding: 8px 16px;
border-bottom: 1px solid #eee;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div class="container" id="clubs">
<div class="filter">
<label><input type="checkbox" v-model="selectedCategories" value="All" /> All</label>
<label><input type="checkbox" v-model="selectedCategories" value="clubParking" /> Parking</label>
<label><input type="checkbox" v-model="selectedCategories" value="clubToilets" /> Toilets</label>
<label><input type="checkbox" v-model="selectedCategories" value="clubFloodlights" /> Floodlights</label>
</div>

<ul class="clubs-list">
<li v-for="club in filteredClubs">{{ club.clubName }}</li>
</ul>
</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

Generating unique triangle patterns through Webgl

Recently, I began learning webgl and have been attempting to create triangles with random sizes and positions similar to the image below using javascript. I understand that I need to utilize a for loop within the function initScene() but I'm uncertai ...

What is the process for integrating the neo4j-graphql library into a GraphQL API?

I am currently working on building a GraphQL API and have set up dummy data for testing purposes. My next step is to connect this GraphQL API to a Neo4j database using the neo4j-graphql library. Can anyone provide guidance on how to establish this connecti ...

CSS style takes precedence over inline JavaScript transitions occurring from a negative position

I am puzzled by a JavaScript fiddle I created which contains two small boxes inside a larger box. Upon clicking either of the buttons labeled "Run B" or "Run C", the corresponding box undergoes a CSS transition that is controlled by JavaScript. Below is t ...

Navigate through the website by transforming the arrow and clicking the link

I am struggling with transitioning my arrow from › (right) to ˇ (down) when toggled. I can't figure out where to place it. If you look at Menu 1 > Submenu 1 > Text with hyperlink I want the 'Text with Hyperlink' to be clickable on ...

Tips for simulating a service in Angular unit tests?

My current service subscription is making a promise: getTaskData = async() { line 1 let response = this.getTaskSV.getTaskData().toPromise(); line 2 this.loading = false; } I attempted the following approach: it('should load getTaskData', ...

Retrieve an identifier from a web address and transmit it to the Laravel controller using VueJS

I'm currently facing an issue with submitting a form in my Vue application. The route I am working with is: http://cricketstats.test/en/dashboard/players/z2d4ca09a7/india/941/runs In this URL, the number 941 represents the player's ID. I need to ...

Having trouble getting videos to load on VueJS?

I've been grappling with loading a video from a local folder in my Vue.js 2 and Laravel project, but haven't had any luck so far. The Vue-loader plugin is properly installed and added in my webpack.config.js as per the documentation: I first at ...

Accessing elements from a controller in a nested ng-repeat in AngularJS

I am relatively new to the world of AngularJS and I've encountered a challenge that I can't seem to figure out. The issue lies within my nested ng-repeat view, as I have a nested comment system. Therefore, the view is built from an object structu ...

Chokidar operates smoothly from the command line, but fails to function properly when invoked through the use of 'npm run'

I've implemented a script that monitors Tailwind CSS files using Chokidar. The script works perfectly when I execute the command in the CLI using chokidar 'tailwind.config.js' --initial=true -c 'npm run build-tailwind'. It successf ...

Using a file readStream within a post handler with Node.js, Request, and Express

Currently, I am utilizing nodejs and express4 for my development tasks. I am facing an issue with a form that has a post method for uploading files as base64, which I am then saving to a gridfs using streams. Below is the code snippet I am working with: ...

Updating the properties of items in an array using React

Today, I was working on React and found myself stuck due to my limited JavaScript knowledge. I am trying to update the "name" property value of any object in this array. Check out the Codesandbox demo: https://codesandbox.io/s/dank-rain-udjcxe?file=/src/ ...

Error encountered during installation of Vuetify in Nuxt: "npm err! [email protected] install: `node build.js || nodejs build.js`"

After creating a Nuxt app using npx create-nuxt-app when running the dev server with npm run dev, I encountered the following error: ╭─────────────────────────────────────── ...

Discover the ID or HREF linked to the current date using moment.js

I'm looking to dynamically add an active class to the current day in my web application. An example of how it currently works is shown below: $( document ).ready(function() { $('a[href*="2208"]').addClass('active'); }); My goal ...

Having trouble retrieving req.session variables in Express/NodeJS?

I have come across various versions of this particular question, however, none of them seem to address my issue directly. My current objective is to establish a Node.js server using Express. Below is my existing server configuration: var express = require ...

Is the state of the React.js component empty?

HTML: <!-- index.html --> <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>React Tutorial</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react.js"></script> ...

Can you provide an alternative code to access an element with the id of 'something' using vanilla JavaScript instead of jQuery's $('#something') syntax

Why am I seeing different console output for $('#list') and document.getElementById("list")? Here is the console printout: console.log($('#list')); console.log(document.getElementById("list")); However, the actual output in the cons ...

Combine the promises from multiple Promise.all calls by chaining them together using the array returned from

I've embarked on creating my very own blogging platform using node. The code I currently have in place performs the following tasks: It scans through various folders to read `.md` files, where each folder corresponds to a top-level category. The dat ...

The jQuery .next() function is applying a class to each element

I am struggling with adding a class to the <a> elements in my Bootstrap 4 Carousel when the slider changes. Currently, my code successfully adds the class .highlight to the next <a> elements, but it adds it to all subsequent elements. Addition ...

I encountered the following error: Failed to parse due to the module '@babel/preset-react' being missing

Encountering a parsing error: Module '@babel/preset-react' cannot be found. Upon creating schema.js, tweetSchema.js, userSchema.js, issues arose with import, export, and export from all three files showing red lines. schema.js: import createSche ...

VueJS: What is the easiest way to create a new instance of a div with just a click of a button?

Is there a way to create a function that will generate a new instance of a specific div (.container in the template) when a button (#addDiv) is clicked, with the button being the only visible element on the webpage initially? I have heard about using docum ...