How to Utilize Vue and Checkboxes for Filtering a List?

My current challenge involves filtering a list of posts based on userId using checkboxes. The data is being retrieved from: https://jsonplaceholder.typicode.com/posts. I aim to include checkboxes that, when selected, will filter the list by userId. Here is my current setup:

var app = new Vue({
  el: '#app',
  data() {
    return {
      jobs: [],
      userIds: ['1', '2', '3'],
      checkedUserIds: []
    }
  },
  created() {
    axios
      .get('https://jsonplaceholder.typicode.com/posts')
      .then(response => (this.jobs = response.data))
  },
  computed: {
    filteredJobs() {
      if (!this.checkedUserIds.length)
        return this.jobs
      return this.jobs.filter(job => this.checkedUserIds.includes(job.userId))
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">

  <div v-for="userId in userIds">
    <input type="checkbox" v-model="checkedUserIds" v-bind:value="userId" /> {{userId}}
  </div>

  <div v-for="job in filteredJobs">
    <h2>{{ job.title }}</h2>
    <div>{{ job.body }}</div>
  </div>
</div>

I am puzzled as to why clicking a checkbox causes the entire list to disappear instead of filtering it by the userId.

Answer №1

Make sure your userIds: ['1', '2', '3'], is an array of strings and not integers. Update it to userIds: [1, 2, 3],

The JSON file contains userId as integers. The data types need to match for the function to operate correctly.

var app = new Vue({
  el: '#app',
  data() {
    return {
      jobs: [],
      userIds: [1,2,3],
      checkedUserIds: []
    }
  },
  created() {
    axios
      .get('https://jsonplaceholder.typicode.com/posts')
      .then(response => (this.jobs = response.data))
  },
  computed: {
    filteredJobs() {
      if (!this.checkedUserIds.length)
        return this.jobs
      return this.jobs.filter(job => this.checkedUserIds.includes(job.userId))
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">

  <div v-for="userId in userIds">
    <input type="checkbox" v-model="checkedUserIds" v-bind:value="userId" /> {{userId}}
  </div>

  <div v-for="job in filteredJobs">
    <h2>{{ job.title }}</h2>
    <div>{{ job.body }}</div>
  </div>
</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

How to Ensure that the Hidden Value of Select Statement in Angular is Always Displayed as Text

Is there a way to customize the top part of a dropdown menu so that it always displays a specific phrase, like 'Symbols' in this case, regardless of the option selected? Currently, the top part shows the last selected symbol, but I want it to be ...

What seems to be the issue with my code for Javascript Math functions?

Welcome to the number game slider! If you roll above 50, you will get double the amount bet. Use the slider to choose your desired betting amount. Issue 1: After a win, the score does not update correctly. Instead of showing increments of 5, it displays s ...

Headers can't be set after they have been sent. This issue arises when calling create(data,cb) function

I am a beginner in Node.js and I am attempting to create a model in MongoDB. However, when I make a call to localhost:3000/a, I notice that the request is being sent twice in the console and I am encountering an error stating "Can't set headers after ...

Can object methods be called using inline event attributes in an HTML tag?

Exploring the depths of core JavaScript has been my latest obsession. It's fascinating how we can easily trigger functions within the global context using events like this. HTML <span class="name" onclick="clicked()">Name</span> JavaSc ...

Caution: It is not possible to make updates on a component while inside the function body of another component, specifically in TouchableOpacity

I encountered this issue: Warning: Trying to update a component from within the function body of another component. Any suggestions on how to resolve this? Interestingly, the error disappears when I remove the touchable opacity element. ...

Is it possible to utilize a variable from a Higher Order Function within a different generation function?

I am facing a dilemma with the need to utilize email = user.email in newcomment['comments/'+id] = {id,comment,email,date}. However, I am unable to incorporate email = yield user.email or yield auth.onAuthStateChanged(user => {email = user.em ...

I'm having trouble with my useState in React/NEXTjs because it's not adding onto the result of a socket.io event from the server, it's simply

Frameworks used: Next.js, Socket.io, React I am currently working on a straightforward messaging application. The main concept involves emitting a message typed by a user, sending that message to the server, and then broadcasting it back to all clients th ...

Steps to resolve the issue: ERROR Avoid nesting VirtualizedLists inside regular ScrollViews. This error can occur even if you are not using ScrollViews

I'm currently working on a react-native app and I need to create a layout with components arranged vertically, including a transaction history section. However, I'm encountering an issue when trying to display the transaction history data from du ...

Implementing an object as a filter in an NG-repeat function

I've created multiple select dropdowns that are populated from a JSON file containing categories. My goal is to use the selections made by users in the dropdowns to filter a list of apps generated using ng-repeat. In my Plunker example http://plnkr. ...

Learn how to default export React with withRouter, all while taking advantage of Material UI's makeStyles

I have been working on integrating Material UI makeStyles with class components, passing useStyles as props while default exporting it in an arrow function. export default () => { const classes = useStyles(); return ( <LoginClass classes={cl ...

How can one use jQuery to target elements that have names that are in an array format?

Is there a way to retrieve the values of these elements and send them as an array using ajax? <input type="checkbox" name="Broadcast[m]"/> Members <input type="checkbox" name="Broadcast[i]"/> IATA agencies <input type="checkbox" name="Bro ...

The jqGrid displays a plus sign even when the subgrid is empty while using XML

I am utilizing jqGrid to display data with a subgrid in XML format. $("#UDFs").jqGrid({ ajaxGridOptions: { contentType: 'application/xml; charset=utf-8' }, datatype: 'xmlstring', datastr: data, xmlReader: { root: "Respo ...

Tips for displaying a div only when the input value is greater than 0, and hiding it when the value is 0

My goal is to display a div whenever the input contains at least 1 character and hide it when the input is empty. Despite my efforts, I can't seem to make it work no matter what I try. Here is my initial attempt: var input = document.getElementById( ...

The player remains unchanged

Hi, I am currently working on my app to update a player's age. To start off, I have added three players: const playerOne = store.dispatch(addPlayer({ firstName: 'Theo', lastName: 'Tziomakas', position: 'Goakeeper ...

When I utilize $router.push() to navigate to a different page, the back button will take me back to the previous page

Within my Vue project, there is an HTML page that I am working on. Here is the link to the page: https://i.sstatic.net/cbtqM.png Whenever I click on the "+"" button, it redirects me to this specific page: https://i.sstatic.net/0rmMD.png This page funct ...

Creating a stunning HTML 5 panorama with GigaPixel resolution

Interested in creating a gigapixel panorama using HTML 5 and Javascript. I found inspiration from this example - Seeking advice on where to begin or any useful APIs to explore. Appreciate the help! ...

Every time I attempt to send a post request, I receive back only the creation date and the unique objectID

Whenever I send a post request, only the created date and objectID are returned. Whenever I send a post request, only the created date and objectID are returned. This issue persists even after multiple attempts. I attempted to verify it using Postman ...

The issue of req.files being undefined in Express.js

I am aiming to upload files to s3 without depending on any middleware like multer. Below is the code snippet of my approach: <form role="form" action="/send" method="post"> <input type="file" name="photo" class="form-control"/> <button ...

How can I retrieve the value from the input field using vue.js?

I am currently utilizing the vue-js-toggle-button library. While I understand that I can access the value inside the name using $refs, the issue arises as I have 3 toggle buttons and cannot set a Ref because I want to retrieve the name value dynamically i ...

Identifying the Back Button in Vue-Router's Navigation Guards

For my specific situation, it is crucial to understand how the route is modified. I need to be able to detect when the route changes due to a user clicking the back button on their browser or mobile device. This is the code snippet I currently have: rout ...