What is the best way to use checkboxes in VueJS to apply filters on a loop and display specific results?

I'm struggling with implementing filters using checkboxes on a list of results and could really use some assistance.

Currently, only the 'All' option is working for applying any filtering logic.

Here is how my HTML looks like with the filters 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="Parking" /> Parking</label>
        <label><input type="checkbox" v-model="selectedCategory" value="Toilets" /> Toilets</label>
        <label><input type="checkbox" v-model="selectedCategory" value="Floodlights" /> Floodlights</label>
    </div>

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

And here's the code inside my VueJS app:

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 club.clubParking === category;
                });
            }
        }
    }
});

I'd appreciate any help as I've been stuck on this issue for hours.

Answer №1

To enhance your filtering process, consider updating the filter criteria based on the category and field.

return vm.clubs.filter(function(club) {
  switch(category){
     case 'Toilets':
      return club.clubToilets;
     case 'Parking':
      return club.clubParking;
     // etc...
  }
});

You can optimize the code by assigning a field name for better readability.

return vm.clubs.filter(function(club) {
  let fname;
  switch(category){
     case 'Toilets':
      fname ='clubToilets';
     case 'Parking':
      fname = 'clubParking';
     // etc...
  }
  return club[fname]
});

Alternatively, you can simplify the process by directly using the selected category as the field name, though this may limit additional logic possibilities.

<label><input type="checkbox" v-model="selectedCategory" value="clubParking" /> Parking</label>
return vm.clubs.filter(function(club) {
  return club[category];
}

The key concept here is to map the category to the corresponding field in your object.

For multiple items:

// Map the field names based on checkbox values. `selectedCategory` should be an array.

const selectedFieldNames =  selectedCategory.map(category=>{
      switch(category){
         case 'Toilets':
          return 'clubToilets';
         case 'Parking':
          return 'clubParking';
         // etc...
      }
})

// selectedFieldNames now contains the names of your object fields

// This will filter and return items with all specified fields set to 'true'
return vm.clubs.filter(function(club) {
  return selectedFieldNames.every(fname=>club[fname])
}

Example Using Your Provided Code Structure.

Note: The code could use some improvements, but it's kept in a format that allows for easy reference.

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: []
},
computed: {
filteredClubs: function() {
var vm = this;
var categories = vm.selectedCategory;
      
if (categories.includes("All")) {
return vm.clubs;
} else {
const selectedFieldNames = categories.map(category => {
switch (category) {
case "ClubToilets":
return "clubToilets";
case "ClubParking":
return "clubParking";
case "ClubFloodlights":
return "clubFloodlights";
}
});

return vm.clubs.filter(function(club) {
return selectedFieldNames.every(fname=>club[fname])
})
}
}
}
});
<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="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>

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

Is it possible to call a JavaScript file located inside a Maven dependency's jar?

In the process of developing a Spring MVC web application using Apache Tiles, I have incorporated JavaScript libraries such as JQuery by including them in the pom.xml file as dependencies. My query pertains to whether I can access these scripts from within ...

In React Native, the onPress handler will continue to be triggered indefinitely after 2-3 presses

import firebase from './Firebase'; import { useState, useEffect } from 'react'; import { StyleSheet, Text, View, Button, FlatList } from 'react-native'; import { TextInput } from 'react-native-web'; import { setStatu ...

"Failure in bundling with NodeJS using nexe and fusebox

I am attempting to convert a nodejs application into an .exe file. I initially tried using pkg, but encountered errors with half of the node-modules. Now, I am experimenting with a different method. However, when I run the following command: nexe index.js ...

What is the best way to call upon a necessary module from various files?

When working with Node.js, I am using Socket.io in my main.js file like this: const io = require('socket.io')(http); Additionally, I have a separate "sub" file called api.js where I delegate some of my business logic. To include this file, I us ...

Unexpected behavior with Node js event listener

I am currently working on emitting and listening to specific events on different typescript classes. The first event is being listened to properly on the other class, but when I try to emit another event after a timeout of 10 seconds, it seems like the lis ...

Store JWT as a cookie in Vue JavaScript and ensure it is successfully saved before proceeding

Upon logging in, my page sends the login and password information to the backend, receives a jwt token in return, saves it to the cookies, and redirects to /home. However, there seems to be an issue with the authentication check on the /home route. When c ...

Ways to switch the visibility of a specific thumbnail

Our team has created a new app that showcases all the videos in our channel. Users can browse through thumbnails and click on one to view the related video, instead of viewing all videos at once. Angular Code $scope.isvideoPlaying = false; $scope.displ ...

Is there a way to confirm whether or not two files are identical?

Is there a reliable method to determine if two files are identical? I've been using a solution that involves downloading the first part of each file, converting the data to base64, and then comparing them. However, I've encountered an issue wher ...

Prevent users from inserting images from their desktop into the HTML by disabling

While working on a HTML5 drag and drop image uploading feature, everything was going smoothly. I had a small div in the HTML with a JavaScript event handler set up like this: $('#uploader').on('dragover', function(e){ ... }).on(&apos ...

Switching between custom dropdowns in Angular

I've implemented a custom dropdown selector with the functionality to toggle when clicked anywhere else on the browser. The toggleModules() function is responsible for handling the toggling within the dropdown. Data: modules=["A", "B", "C", "D", "E", ...

Avoid Refreshing the Page When Pressing the Like Button

I've been working on code for liking a post and saving the value to a database using server-side code. However, I'm running into some issues when the page refreshes after clicking the like button. I tried using event.preventDefault() in my JavaSc ...

Unable to view options in Vuetify's v-select component

Having an issue with a component that is supposed to grab the address from a user, specifically the state. Despite following the documentation closely, I am unable to figure out why the options are not visible when clicking the button. It works fine when ...

Prompt user to save changes or cancel before closing modal (if closed by pressing ESC or clicking the backdrop)

When I manually close the modal, everything works fine. I just create a prompt and only call the BsModalRef.hide() method when the prompt (sweetalert) is closed. However, when the modal is closed using the ESC key or click-outside events provided by Boots ...

Sending an AJAX request to submit a form and receiving a response

I am in the process of developing a Rails application and I am seeking a way to submit a form using Ajax. This functionality is crucial as I want the form submission to occur without causing a full page reload. Initially, I tried using form_remote_tag but ...

I am unable to display my JSON data in Next.js using a fetch request

I'm having trouble understanding the code, and it seems like the API is open to anyone since it's just a simple JSON. However, I keep getting an error: Error Message: Reason: `undefined` cannot be serialized as JSON. Please use `null` or omit th ...

Guide on how to load just the content section upon clicking the submit button

Here is an example of my code: <html> <head> <title>Test Loading</title> </head> <body> <div id="header"> This is header </div> <div id="navigation" ...

Protractor Cucumber: Issue with locating spec file patterns (identifying 2 features)

I am facing an issue with running 2 different cucumber features. After adding the following lines to my protractor.conf.js file: specs: ['add.feature', 'delete.feature'] I encountered a problem when running the tests stating pattern ...

AngularJS: monitoring changes in an array property

For the problem at hand, take a look at this link: http://plnkr.co/edit/ZphAKvZeoVtuGFSEmOKg?p=preview Imagine you have an array structured like this: var arr = [ { 'a': "123", 'b': "654" }, { 'a': "456", &apo ...

Can the useNavigation hook be used to navigate to a class component in React?

How can I use the useNavigation hook to navigate to a class component? Here is my class: export default class AzureLogin extends React.Component I want to navigate to AzureLogin from Screen1. What is the correct way to achieve this? import { useNavigati ...

Conceal a table row (tr) from a data table following deletion using ajax in the CodeIgniter

I am attempting to remove a record in codeigniter using an ajax call. The delete function is functioning correctly, but I am having trouble hiding the row after deletion. I am utilizing bootstrap data table in my view. <script> function remove_car ...