Filter arrays in Vue.js using checkboxes

I'm currently working with vuejs and I need to implement a filtering feature for my array using checkboxes. I attempted to use v-model to filter the array based on three specific options: "Truck," "Van," or "Tx". However, I haven't been successful in achieving the desired outcome. Additionally, I would prefer not to utilize a computed method for this task.

new Vue({
  el: "#app",
  data: {
  selection:[],
    todos: [
          {
    "Name": "CHS_200_TL_L62_TRUCK"
  },
        {
    "Name": "VHS_600_TL_L62_TRUCK"
  },
  {
    "Name": "VHS_116_TL_L62_TRUCK"
  },
  {
    "Name": "VHS_146_TX_L62_VAN"
  },
    {
    "Name": "VHS_613_TL_L62_TRUCK"
  },
  {
  "Name":"JE_50_OL_T62_TRUCK"
  },

  {
    "Name": "VHS_T10_OL_L62_TRUCK"
  },
    {
  "Name":"JE_59_OL_T62_TRUCK"
  },
      {
    "Name": "LEE_100_TL_L62_TRUCK"
  }
    ],

  mounted:function(){

  },
  methods: {
  
}

    
  },
  methods: {
    fin: function(todo){
        todo
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script> 
<div id="app">
  <h2>Todos:</h2>
<input type="checkbox" id="vehicle1" name="vehicle1" value="Truck" v-model="checkedNames"> Truck<br>
<input type="checkbox" id="vehicle2" name="vehicle2" value="Van" v-model="checkedNames"> Van<br>
<input type="checkbox" id="vehicle3" name="vehicle3" value="TX" v-model="checkedNames">
<label for="vehicle3"> TX</label><br>
  
 
    <li v-for="todo in todos">
{{todo.Name}}
    </li>
  
</div>

Answer №1

If computed property isn't your preference, you can utilize a watcher:

new Vue({
  el: "#app",
  data() {
    return {
      selection:[],
      filtered: [],
      todos: [{"Name": "CHS_200_TL_L62_TRUCK"}, {"Name": "VHS_600_TL_L62_TRUCK"}, {"Name": "VHS_116_TL_L62_TRUCK"},  {"Name": "VHS_146_TX_L62_VAN"}, {"Name": "VHS_613_TL_L62_TRUCK"}, {"Name":"JE_50_OL_T62_TRUCK"}, {"Name": "VHS_T10_OL_L62_TRUCK"}, {"Name":"JE_59_OL_T62_TRUCK"},   {"Name": "LEE_100_TL_L62_TRUCK"}],
    }
  },
  watch: {
    selection: {
      handler() {
        this.filtered= []
        if (this.selection.length) {
          this.todos.forEach(t => {
            this.selection.forEach(s => {
              if (t.Name.split('_').find(w => w === s.toUpperCase())) {
                if (!this.filtered.find(f => f.Name === t.Name)) this.filtered = [ ...this.filtered, t]
              }
            })
          })
        } else {
          this.filtered = [...this.todos]
        }
      },
      deep: true,
      immediate: true
    }
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <h2>Tasks:</h2>
  <input type="checkbox" id="vehicle1" name="vehicle1" value="Truck" v-model="selection"> Truck<br>
  <input type="checkbox" id="vehicle2" name="vehicle2" value="Van" v-model="selection"> Van<br>
  <input type="checkbox" id="vehicle1" name="vehicle1" value="TX" v-model="selection"> TX<br>
  <ul>
    <li v-for="task in filtered">
      {{task.Name}}
    </li>
  </ul>
</div>

Answer №2

Let's address the typos present in your code :

  • You have defined selection:[] in the script, but in the template, you are using checkedNames which is not defined. To solve this issue, you should use a computed value that looks for todos containing selection
  • Add a computed value named todosFiltered in your script
...
computed: {
    todosFiltered() {
      return this.todos.filter((todo) => {
        return this.selection.every((select) => todo.Name.toLowerCase().includes(select.toLowerCase()));
      });
    },
  },
....

  • Replace references of todos with todosFiltered in your template
<template>
  <div id="app">
    <h2>Todos:</h2>
    <input
      type="checkbox"
      id="vehicle1"
      name="vehicle1"
      value="Truck"
      v-model="selection"
    />
    Truck<br />
    <input
      type="checkbox"
      id="vehicle2"
      name="vehicle2"
      value="Van"
      v-model="selection"
    />
    Van<br />
    <input
      type="checkbox"
      id="vehicle1"
      name="vehicle1"
      value="TX"
      v-model="selection"
    />
    <label for="vehicle1"> TX</label><br />

    <li v-for="todo in todosFiltered">
      {{ todo.Name }}
    </li>
  </div>
</template>

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

The output generated by grunt-contrib-handlebars differs from that of the handlebars npm task

Looking for some help with a problem similar to the one mentioned in this Stack Overflow question. Since that question hasn't been answered yet, I decided to create my own post. I'm currently attempting to precompile my handlebars template files ...

Tips for creating responsive elements with a z-index of 1 in CSS

I have implemented the code provided in a codepen tutorial, but I replaced the world map image with a USA map. However, the dots are not responsive due to the z-index=1 specified on them. I experimented with vh, vw, and percentages, yet when I resize my s ...

troubles encountered in implementing JavaScript to toggle the display of content upon clicking a link

Here is the code below. Upon page load, the form data will be hidden. When clicking on the comment link, it will toggle the visibility of the form content. Clicking on the comment link again will show the hidden content once more. What is desired is to ha ...

"Why does adding a new span create space between it and the previous ones, and what can be done to prevent this from

Essentially, it creates the equation "a + b = c". However, I need to create "a + b = c" instead. HTML: <div class="container"> <span id="b__value">+b</span> <span id="c__value">=c</span> &l ...

Exception in posting strings or JSON with react.js

Whenever a user clicks on the Signup button, the process I follow to create an account is as follows: Firstly, a new User entry is created in the database. createUser = () =>{ var xhr = new XMLHttpRequest(); xhr.open('POST', 'http:// ...

Transforming a single object into several arrays

I have a JSON file called "icon.json" that contains the following data: [ { "name": "happy", "url": "1.gif" }, { "name": "excited", "url": "2.gif" }, { "name": "surprised", "url": "3.gif" ...

What is the most effective way to determine if a statement is either false or undefined?

What is the most effective way to determine if a statement is not true or undefined, sometimes without necessarily being a boolean? I am attempting to improve this code. var result = 'sometimes the result is undefined'; if (result === false || ...

Launching PDF on IE11 in a new tab seamlessly without any prompts - mssaveoropenblob

We are in the process of transitioning an ASP.NET MVC application that used to have the functionality of opening a PDF file in a new tab using FileContentResult. return new FileContentResult(byteArray, "application/pdf"); As part of this migration to Rea ...

What is the best way to incorporate images from an external module into my React project?

Is there a way to include images from an external module (npm install external-module) in my project's public assets? The images are located in the directory path myProject/node_modules/external-module/dist/img. ...

Making a column in a Vue data grid return as a clickable button

My goal is to utilize vue.js grid to display multiple columns with calculated text values, along with a clickable column at the end that triggers a dynamic action based on a parameter (such as calling an API in Laravel). However, when I include the last c ...

Convert the data into a format that is compatible with JavaScript

Having trouble extracting a value from json and placing it into my controller. I want to assign the membership value of 8 to $scope.value = data.membership; Service call in JS: .service('getMembership', function ($http, SERVER_URL) { r ...

The es6 object class is not defined

Hey there, I'm currently working on a simple pong game and encountering an issue with passing the player object into drawPlate. It seems to be printing the information correctly, but then I get hit with an Uncaught TypeError exception. The data print ...

Warning from Vue: Steer clear of directly changing a prop as it will be replaced whenever the parent component undergoes re-rendering

I've been diving into Vue.js, but I'm encountering an issue. Every time I try to click on the "edit age" or "change my name" button, I get the following error message. [Vue warn]: Avoid mutating a prop directly because the value will be overwrit ...

Verify whether a div element is styled in a specific manner

Upon initial load of my website, if the page is maximized or in fullscreen mode, the comBrand div will have specific CSS properties applied. However, during a resize event, I use the .css() function to adjust the properties of this element so it doesn&apos ...

Is it possible for Cypress to execute test files that are imported from outside of the Cypress folder

Currently, I am developing an E2E test framework using Cypress and encountered an issue while trying to import spec files from locations outside the traditional Cypress directory structure (which includes directories for fixtures, integration, plugins, and ...

VueJS fails to display table information

I am facing an issue with rendering data from my API using VueJS 2. Although the backend services are successfully sending the data, the HTML table does not display it. There are no errors shown in the debug console, and even the Vue Debug extension for Fi ...

Manipulating arrays in JavaScript through HTML processing

I'm encountering an issue while trying to send an array to a JavaScript function. Here's what I have so far: Within the controller: @data = [{date: '2014-08-17'}, {date: '2014-08-20'}].to_json In the view: <%= content_t ...

Struggling to connect CSS and JavaScript files to index.html on Heroku while utilizing Node.js

Trying to set up a Tic Tac Toe game in my app.js file, but encountering some issues with linking files in index.html. app.set('port', (process.env.PORT || 5000)) //serve static files in the public directory app.use(express.static('public& ...

Using Typescript to set a custom timeout duration based on a dynamic variable within a for loop

My function includes a timeout that changes every 3 seconds: setActiveImage(promotions) { for (let i = 0; i <= promotions.length - 1; i++) { setTimeout(()=> { this.activeImage = 'http://myrul/public/Commercials/' + promo ...

"Is there a way to modify the color of the button once it's been clicked, but only for the specific button that was

Looking to create a Quiz App using React and facing an issue where all buttons change color when clicked, instead of just the one that was clicked. Any solutions on how to make only the clicked button change its color in React.js? App.js import Main from ...