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

Single input results in array output

I have a pair of items in this array list. $.each(data.recalls,function(i) { var recall = data.recalls[i].nnaId; var description = data.recalls[i].remedyDescription; console.log(recall); console.log(description); $('textarea[name= ...

Printing Apex Oracle reports using Internet Explorer

I am facing a challenge with printing my page that contains two interactive reports. To enable printing, I have utilized a JavaScript function that triggers window.print(). I have incorporated CSS to adjust the layout of my tables when printed. @media pr ...

What could be causing Next.js to throw an error upon completion of the MSAL OAuth process?

I encountered an error while building a website using next.js. The site is set up for production, and after the authentication process with MSAL for Azure AD integration, I am facing the below error during the OAuth loop. As a beginner in next.js coming fr ...

Facebook and the act of liking go hand in hand, growing together

I am working on a website where I want to include Facebook like and share buttons with counters. To achieve this, I used Facebook's own links to generate these buttons for the specific URL. The issue I encountered is that when I like or share the page ...

Develop a personalized API using Strapi that involves integrating data from two distinct tables

I am relatively new to Strapi, so please forgive my lack of experience. My goal is to set up a custom route for retrieving complex data using two related tables. I have relationships with the "items" and "comments" tables. My approach involves selecting ...

Ways to prevent the "Site not secure" warning on an Express server with HTTPS configuration

In the process of creating an Express app, I decided to enable HTTPS for a secure connection. After obtaining a certificate from StartSSL.com and importing it into my server successfully, everything seemed set up correctly. However, an issue has arisen: W ...

How can I enable a button in a React application when the text input is not populating

For my Instagram MERN project, I have implemented a Comment box feature for users. The Post button starts off disabled and becomes enabled when text is entered. However, despite entering text, the button remains disabled, preventing submission. Below is th ...

The KeyboardAvoidingView disrupts the structure of the flexbox layout

Check out this code snippet: return ( <KeyboardAvoidingView style={{ flex: 1 }} behavior="padding" enabled> <View style={style.flex1}> <View style={style.imageContainer}> <Image style={style.image} ...

Tips for providing arguments in the command line to execute a yarn script

Just starting out with JavaScript. I understand that npm allows for passing variables in the command line using process.env.npm_config_key like this: npm run --key="My Secret Passphrase" test:integration How can I achieve the same thing with yarn? I&apo ...

Setting up webpack-hot-middleware in your express application: A step-by-step guide

I am in the process of enabling webpack HMR in my express application. This is not a Single Page Application (SPA). On the view side, I am utilizing EJS and Vue without vue-cli, which means I have to manually set up the vue-loader for the .vue files in web ...

Concealing and Revealing a Div Element in HTML

Every time the page is refreshed, I am encountering a strange issue where I need to double click a button in order to hide a block. Below is the code snippet for reference: <!DOCTYPE html> <html> <head> <meta name="viewport&quo ...

It is impossible to add a new element between two existing elements that share the same parent

I'm attempting to place an <hr> tag between the first and second .field-container. Because they have the same parent, I thought using element1.parentNode.insertBefore(element2, ...) would be the solution. However, it is not working as expected a ...

arrange the elements in an array list alphabetically by name using the lodash library

Is there a way to alphabetically sort the names in an array list using JavaScript? I attempted to achieve this with the following code: const sample = [ { name: "AddMain", mesg: "test000" }, { name: "Ballside", ...

developing an associative object/map in JavaScript

I have a form featuring various groups of checkboxes and I am attempting to gather all the selected values into an array, then pass that data into an Ajax request. $('#accessoriesOptions input').each(function(index, value){ if($(this).prop(& ...

Using JQuery and JavaScript to store and dynamically apply functions

I have a code snippet that looks like this:. var nextSibling = $(this.parentNode).next(); I am interested in dynamically changing the next() function to prev(), based on a keypress event. (The context here is an input element within a table). Can someo ...

Experience the power of module federation in Next JS without using the @module-federation/nextjs-mf package

Currently transitioning from Java to JavaScript, I am working on a Next.js project. I have a requirement to share the client component from this Next.js project with another project built on React. Upon discovering module federation, I successfully created ...

Transforming the response.render method in Express to be a promise-enabled

I have a task at hand where I need to develop a render method that constructs HTML blocks into a string. Initially, it appears to be working fine, but I ended up using the infamous "new Promise" and now I'm not sure if my approach is correct. Here&apo ...

JavaScript form validation issue unresolved

When I attempt to validate form fields using Javascript functions, they seem to not load or check the field upon clicking the submit button. <html> <body> <?php require_once('logic.php'); ?> <h1>New Region/Entit ...

Using an image as an onclick trigger for a JavaScript function

I am working on a registration page as part of my university project where users can create an account and store their information in a MySQL database. One feature I'm implementing is the ability for users to select an avatar picture. Below is the co ...

In Vuejs 3, the variable $el is currently not defined, but $ref holds the object

I can't seem to access the element of a textbox in my code. Even though $el is undefined, $ref contains the object. What am I missing here? I've simplified my code for clarity. Thank you! app.component('lit-entry', { templa ...