Using VueJS for interactive checkbox filtering

This marks the beginning of my VueJS project, as I transition from jQuery. My main goal is to filter a grid using multiple checkboxes. In the JavaScript code provided, there is a filterJobs function that filters an array based on the values checked (v-model="checkedLocations"). It seems like the array.includes method only filters on a single value, but I want to be able to filter on multiple values without modifying the original array. If a user unchecks a location, I don't want it to disappear completely and not rebind.

let careers = careers || {};

 careers.taleo = (function($){

   let app;

   let init = function() {

    app = new Vue({
      el: '#app',
      data: {
        locations: ['Scottsdale, AZ','Chandler, AZ','Irvine, CA','Denver, CO','Chicago, IL','Rockville, MD','Kansas City, MO','Charlotte, NC','Red Bank, NJ','Henderson, NV','Melville, NY','Allentown, PA','Irving, TX'],
        jobs: null,
        checkedLocations: []
      },
      created: function () {
        this.fetchData();
      },
      methods: {
          fetchData: function () {
            this.jobs = [
              { id: '1', title: 'Circuit Court Clerk', description: 'lorem ipsum', location: 'Charlotte, NC', department: 'Sales and Marketing', date: '23/10/17' },
              // Add more job entries
            ];
          },
          filterJobs: function(event) {
            app.jobs = app.jobs.filter(function (job) {
              return job.location.includes(app.checkedLocations);
            });
          }
        }
    });



   };


   return { init, app };

})();

(function(){
  careers.taleo.init();
})();

https://codepen.io/neil/pen/WjXrxx

Answer №1

Consider utilizing a computed value for your filtered locations.

computed:{
  filteredJobs(){
    // If there are no checked locations, return all jobs.
    // You can remove this if you only want to return 
    // checked locations.
    if (!this.checkedLocations.length)
       return this.jobs

     return this.jobs.filter(job => this.checkedLocations.includes(job.location))
  }
}

Make sure to adjust your template accordingly.

<div class="job" v-for="job in filteredJobs">

You should also eliminate your filterJobs method.

Here is an example.

Essentially, the recommended approach is to update your filter logic to:

this.checkedLocations.includes(job.location). 

Additionally, it's better to avoid altering your data every time you apply a filter to prevent data inconsistencies. Using a computed property aligns more with Vue best practices.

Answer №2

When listing jobs, incorporate the v-if directive into the line:

<div class="job" v-if=filterJobs(job) v-for="job in jobs">

To implement the filterJobs method, use this structure:

filterJobs: function(data) {
        if (this.checkedLocations.length == 0) return true;
        return this.checkedLocations.includes(data.location);
}

View the updated code here

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

What steps should I follow to ensure that the content for the back page is printed on the back page of a booklet when using paged.js?

In the case of a booklet printed from folded sheets, it is interesting to note that the number on the back page will always be divisible by 4. If the content does not have a multiple of 4 pages, then the back page will end up inside the booklet. For my cu ...

Incorporate FontAwesome global components into your Vue project using TypeScript

Hey there, I'm a TypeScript newbie and looking to incorporate FontAwesome icons into my Vue 3 App. Here's the setup: Here is my main.ts : import Vue, { createApp } from 'vue'; import './registerServiceWorker'; import { librar ...

Ways to block past dates on bootstrap date picker starting from the current date and how to prevent dates beyond 90 days in the future from being selected on the

I am currently facing an issue with disabling previous dates from the current date in my code. While the functionality works well for the "From Date" date picker, I am having trouble implementing the same restriction for the "To Date" date picker after 90 ...

What is an alternative way to show the contents of a JSON file without directly accessing it

Recently, I stumbled upon an amazing website - where I have been exploring to learn something new. The website prominently features the use of Ajax and some fascinating javascript without any additional libraries. Within a single javascript file on this ...

Angular encountered a SyntaxError due to an unexpected curly brace } character

After spending a lengthy hour trying to troubleshoot this issue, I am at a loss as to why it is not functioning correctly. I have been attempting to showcase a row of images on a webpage using Angular based on data fetched from a json file. Unfortunately, ...

When using JSON.stringify, the output is null. However, when using document.write, the data

I am currently working on a plugin for crawljax that involves executing some JavaScript code, similar to the following: String result = browser.executeJavaScript(script).toString(); The script code is as follows: function getElementPosition(id) { var el ...

What is the best method to extract and manipulate data from a JSON file in an AngularJS application?

personManagerInstance.getString("firstname",'common','en') I am currently passing a direct string in the UI which is affecting it. What I actually need is to read the data from a JSON file and return it as a string. personManagerInstan ...

Querying with jQuery to Retrieve HTML from Elements with the Same Class

Greetings Everyone! Please take a look at my code... <font class="detDesc" > Uploaded 07-11&nbsp;2012, Size 105.79&nbsp;MiB, ULed by <a class="detDesc" href="/somelink" title="somelink title">somelink</a> </font> ...

Can someone please show me the process of iterating through an array in vuejs?

I am trying to create a Vue.js method that loops through an array of objects and returns all the names in that array. However, I am not sure how to achieve this. The method implementation would look something like this: fruits =[ {name: "apple", calori ...

modified a file using express framework

I am attempting to utilize mongoDB in order to update the status of an existing document. Despite my backend successfully receiving the routes, the mongoDB update process is not functioning as expected. router.post('/orders_drivers', function (r ...

Getting Bootstrap columns to work well with Angular ng-show

I am working with three columns in Bootstrap, all set to col-md-4 width. The middle column has an ng-show attribute that may hide it at times. When the rightmost column becomes visible due to friend requests, it displaces the middle column if it's hid ...

Is there a method to add HTML code statically rather than in a dynamic environment?

I'm currently in the process of developing a front-end website with no backend code, as I plan to host it on GitHub pages. I feel that adding any additional backend functionality would be unnecessary. Is there a simple method to incorporate common el ...

Executing a for loop concurrently by utilizing async/await promises

In my current code, I am using a for loop structured like this: async myFunc() { for (l of myList) { let res1 = await func1(l) if (res1 == undefined) continue let res2 = await func2(res1) if (res2 == undefined) continue ...

What is the best way to integrate Greensock CustomEase with TypeScript?

Currently, I am developing a game using Typescript with PixiJS and GreenSock (or is it GSAP?) for handling all the tweening. I recently encountered a situation where I needed to implement some custom easing using cubic-bezier curves. GreenSock provides a C ...

Retrieving all options from a dropdown list in HTML using ASP.net C#

I am currently working with a select list that looks like this: <select name="Section" id="Section" size="5"> <option>Section1</option> <option>Section2</option> <option>Section3</option> <option>Section4< ...

Disabling data-scroll-speed on mobile devices

As a beginner in JavaScript/jQuery, I am working on incorporating code that changes the scrolling speed of specific elements on my webpage. However, I am struggling to disable this code for smaller screen widths. Here is the code snippet I have so far: &l ...

generate iframes on secure websites

I'm in the process of developing a bookmarklet. Essentially, it retrieves a snippet of JavaScript code from the server and generates an iframe on websites with different domains. While it operates smoothly on http websites, it appears to be restricte ...

I'm currently working on storing my data in a Node.js REST API, but I keep encountering an issue with the error message "req.status is not a function"

router.post('/savedata',function(req, res){ console.log(req.body); var data={ firstname:req.body.firstname, lastname:req.body.firstname, password:req.body.password, email:req.body.email, created:req ...

Shift the element within the div towards the left side

I am trying to create an animation for an element that moves to the left when hovered over, but the code I thought was correct doesn't seem to be working in my fiddle. Here is the link to the fiddle I created: https://jsfiddle.net/feb8rdwp/3/ Based ...

Converting the given data into an object in JavaScript: a step-by-step guide

"[{'id': 3, 'Name': 'ABC', 'price': [955, 1032, 998, 941, 915, 952, 899]}, {'id': 4, 'Name': 'XYZ', 'id': [1016, 1015, 1014, 915, 1023, 1012, 998, 907, 952, 945, 1013, 105 ...