Working with multiple checkboxes in Vue.js - A detailed guide on filtering data

My code for combining filter, sort, and search is functioning well.

<template>
  <h5>List of Products</h5>

        <h3>Filter</h3> 
        <button v-on:click="resetOptions">Reset</button>
        <button v-on:click="sorting">Sorting</button>
        <button v-on:click="sorting2">Sorting2</button>
        <select v-model="category">
            <option value="Accessories">Accessories</option>
            <option value="Laptop">Laptop</option>
            <option value="Stationary">Stationary</option>
        </select> 
        <div>
        <input type="checkbox" name="test" id="test" v-model="city" value='Roma' @change="uniqueCheck">
        <label for="test"> Roma</label>
        <input type="checkbox" name="test2" id="test2" v-model.trim="city" value='Barselona' @change="uniqueCheck">
        <label for="test2"> Barselona</label>
        <input type="checkbox" name="test3" id="test3" v-model.trim="city" value='Milano' @change="uniqueCheck">
        <label for="test3"> Milano</label>
        </div>


        <input type="text" v-model="name" placeholder="Filter By Name"/>

        <label for="vol">Price (between 0 and 1000):</label>
    
        <input type="range" v-model.trim="range" min="0" max="1000" step="10"/>  
        <ul>
            <li v-for="product in filterProducts" :key="product.name"> Product Name : {{product.name}} - Price : {{product.price}} ({{product.category}}) 
                {{product.city}}
            </li>
        </ul>
</template>

<script>
export default {
 data: ()=> ( {

           
            city:[ ],
            category: '',
            name: '',
            range: '10000',
            products: [
                { name: "Keyboard", price: 44, category: 'Accessories', city:'Roma'},
                { name: "Mouse", price: 20, category: 'Accessories', city:'Barselona'},
                { name: "Monitor", price: 399, category: 'Accessories', city:'Roma'},
                { name: "Dell XPS", price: 599, category: 'Laptop', city:'Roma'},
                { name: "MacBook Pro", price: 899, category: 'Laptop', city:'Roma'},
                { name: "Pencil Box", price: 6, category: 'Stationary', city:'Barselona'},
                { name: "Pen", price: 2, category: 'Stationary', city:'Milano'},
                { name: "USB Cable", price: 7, category: 'Accessories', city:'Milano'},
                { name: "Eraser", price: 2, category: 'Stationary', city:'Roma'},
                { name: "Highlighter", price: 5, category: 'Stationary', city:'Roma'}
            ]

        }),

              computed: {
            filterProducts: function(){
                return this.filterProductsByName(this.filterProductsByRange(this.filterProductsByCity(this.filterProductsByCategory(this.products))))
            },

        },
        
        methods: {

            filterProductsByCategory: function(products){
                return products.filter(product => !product.category.indexOf(this.category))
            },

            filterProductsByName: function(products) {
                return products.filter(product => !product.name.toLowerCase().indexOf(this.name.toLowerCase()))
            },

            filterProductsByCity: function(products) {
                return products.filter(product => !this.city.includes(product.city))
            },

            filterProductsByRange: function(products){
                return products.filter(product => (product.price >= 0 && product.price <= this.range) ? product : '')
            },

            sorting:function(){
                this.products.sort((a,b)=>(a.price > b.price) ? 1 : -1)
            },
             sorting2:function(){
                this.products.sort((a,b)=>(a.price < b.price) ? 1 : -1)
            },

            uniqueCheck(e){
            if (e.target.checked) {
                 this.city.push(e.target.value);
               } else {
                 const index = this.city.indexOf(e.target.value);
                 if (index !== -1) {
                    this.city.splice(index, 1);
                 }
               }
         },

            resetOptions:function(){
                this.category='',
                this.city=[],
                this.name='',
                this.range='1000'
            },
        },

}
</script>

<style>

</style>

I would like to implement multiple checkboxes filters. For instance, when selecting 'Barcelona' and 'Roma,' I expect the display to show products with cities 'Barcelona' and 'Roma.' The current code does not support this due to the @change function. I attempted without it but encountered issues as shown below:

https://i.sstatic.net/10xvf.gif

Are there alternative ways to incorporate this additional filter?

Answer №1

The method you are using to filter products by city is incorrect.

You need to ensure that the product's city is included in your this.city property when filtering.

Whenever you select checkboxes, their values will be added to the city property like this:

For example: ['london', 'paris']

To fix this issue, you can use the following code snippet:

filterProductsByCity: function(products) {
    return products.filter(product => this.city.indexOf(product.city) !== -1)
}

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

Modify components in a directive template depending on the information in the scope

In my project, I am facing an issue with a directive nested within an ng-repeat. The ng-repeat item is passed to the directive and I am trying to generate a directive template or templateUrl with dynamic elements based on a key/value in the item. Specifica ...

Adding items to the array from user input triggered a Core Dump with a Segmentation fault error

I created a sorting algorithm for an array, and now I'm attempting to implement it using input elements. However, when I try to execute the code, the compiler displays the error "Core Dump (Segmentation fault)". int array[100]; int num; printf("Plea ...

Vue computed property for calculating total in a nested array

I am currently working with vue-cli and I am trying to find a way to calculate the total number of active tasks in the Tasks array. Tasks: [ {name: 'Sam', available: [{active: 'yes', day:'Mon'},{active: 'yes ...

What could be causing the "ERROR TypeError: Cannot read property 'length' of undefined" message to occur with a defined array in my code?

Even though I defined and initialized my array twice, I am encountering a runtime error: "ERROR TypeError: Cannot read property 'length' of undefined." I have double-checked the definition of the array in my code, but Angular seems to be playing ...

Enhancing Values Across a Timeframe Using JavaScript

Last time, I asked about my code. Here is what I have currently: var secs = 100; setInterval(function() { var $badge = $('#nhb_01'); $badge.text((parseFloat($badge.text())+0.01).toFixed(2)); }, secs); I want the counter to increase by ...

Vue 3 has officially deprecated the use of ::v-deep as a combinator. Going forward, please utilize ::v-deep(<inner-selector>) instead

Recently, an error message has been popping up in Vue 3 regarding the use of ::v-deep. The warning states that using ::v-deep as a combinator is deprecated. Instead, it recommends using ::v-deep(<inner-selector>) Here is an example of the CSS ...

Unable to invoke function within class using 'this'

I've been working on a class named Scheduler that runs a cron job using the cron module. I've defined a function to calculate the difference in days between two dates, and it works fine when called outside of the cron job iteration. However, if I ...

Having difficulty saving information in a .json file

I'm currently facing an issue with my ionic framework hybrid application. My goal is to save values from three input boxes into a 'data.json' file, and be able to retrieve or modify that data as needed, ensuring that the values persist even ...

What is a way to hide or exclude tabs when there is no content to display for a particular tab in Vue?

I'm new to javascript and Vue, and I'm trying to figure out how to hide tabs that don't contain any information. I want to display only the tabs that do have information. Can someone please help me with this? I automatically pull images bas ...

Develop a personalized grid layout with specific rows and columns utilizing ReactJS

Is there a way to create a personalized box based on user input dimensions? For example, if the user specifies 4 columns and 5 rows, can a box of size 4x5 be generated allowing the user to navigate through the boxes using arrow keys? <input type=" ...

React ESLint issue detected at a phantom line

When attempting to build in nextjs using next build, an error occurs with references to line 19 (an empty line) and line 33 (which does not exist). Despite updating the version of eslint-plugin-react in my package-lock.json file to ">=7.29.4", ...

Exploring the application of Nested Maps in extracting parameters for the getStaticPaths

Your data structure is organized like this: data = { "cse": { "first": [ "Computer Hardware Essentials", "Computer System Essentials", "Cultural Education" ], "second&qu ...

JavaScript's GET method fails to retrieve the complete JSON file

I am facing an issue with a substantial JSON file that my JavaScript code is unable to pull in entirely. When I check the Network tab in Firefox developer tools, it shows that the data stops at around line 57,301 out of 528,342 lines in the JSON file. Ini ...

What is the best method for showing the price from this list of items?

{"item":{"icon":"ANOTHER LINK","icon_large":"ANOTHER LINK","id":385,"type":"Default","typeIcon":"ANOTHER LINK","name":"Shark","description":"I should be cautious when consuming this.","current":{"trend":"neutral","price":"1,239"},"today":{"trend":"positive ...

The attribute 'checked' is not a valid property for the 'TElement' type

Learning about typescript is new to me. I have a functional prototype in fiddle, where there are no errors if I use this code. http://jsfiddle.net/61ufvtpj/2/ But in typescript, when I utilize this line - if(this.checked){ it presents an error [ts] Pro ...

Display a different image while another image is in the process of loading

I am currently facing an issue with a div that has a background image set up as follows: <div class="carousel-image" style="background: url(img/background.gif) no-repeat center center;"> </div> Upon loading my webpage, there is a brief ...

Tips for transforming a scroll element into the viewport using Angular 2+

This is a sample Here is a component with a list of items: class HomeComponent { text = 'foo'; testObject = {fieldFirst:'foo'}; itemList = [ '1', '2', '3', & ...

Retrieve the values of elements

Is there a reliable way to retrieve an element's clientWidth and scrollWidth? I've tried using getCssValue, but it doesn't seem to work. $('.grid-header-col .title').getCssValue('scrollWidth') ...

How can jQuery input be incorporated in a form submission?

My current form includes a field for users to input an address. This address is then sent via jQuery.ajax to a remote API for verification and parsing into individual fields within a JSON object. I extract the necessary fields for processing. I aim to sea ...

Real-time database logging triggered by Firebase user authentication

exports.setupDefaultPullups = functions.auth.user() .onCreate( async (user) => { const dbRef= functions.database.ref; let vl= await (dbRef.once('value').then( (snapshot) => { return snapsh ...