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

"Unleashing the Power of MongoDB's Dynamic $in

Is there a way to dynamically pass a list of strings to a $in clause in MongoDB? I attempted the following code, but it didn't work and I haven't been able to locate more information other than an example with hardcoded values. The restrictedUs ...

An argument error in IE 8 caused by an invalid procedure call

Is there a way to access the opener's class in a child window created using window.open? This works smoothly in W3C browsers, but fails in IE 8. On the other hand, I tested using an iframe and it seems to work fine across all browsers. The main goal o ...

handle an exception within the initializer of its object

I'm currently working with an Ajax object that is utilized in various other objects to load 'Json' files. One issue I'm facing is trying to catch the 404 'Not found' exception thrown in the initializer object. However, every ...

"Tips for retrieving properties from a JSON object that has been converted to a string

I'm facing an issue with retrieving the url from a response in my code. The goal is to use this url for navigation using the router function. Here's the problematic code snippet: const redirectToStripe = async () => { const response = await ...

Creating a sleek and modern web application using Laravel 5 and Vue JS

Using Vue JS in my Laravel 5 application is causing a blank page to appear when I use v- new Vue({ el: '#vApp', data: { todos: [ { text: 'Learn JavaScri ...

What is the best way to retrieve the value of a dynamically created button in code?

I am dealing with a situation where I have a button that is supposed to fetch some data based on the classroom ID. button(type='button' id='getButton', onclick='get()', value=classroom.id ) Class Students Additionally, I ha ...

jQuery ajaxSetup: handling error retries for ajax calls is not possible

When using $.ajaxSetup(), I am faced with the challenge of making an AJAX request after refreshing a valid token in case the previous token has expired. The issue arises when attempting to execute $.ajax(this) within the error callback. $.ajax({ url: ...

How to apply styling to a specific portion of text within a list element using Vue.js

Despite my best efforts, I am struggling to style only the word "healthy" within the 'It is healthy!' string using computed properties, watchers, and methods in vuejs. I'm at a loss for how to achieve this unique styling. <template> ...

Issue with Backbone Event Dropping Functionality

I am facing an issue with my dashboard that has two backbone Views. One of the views consists of various drop zones while the other contains items with draggable="true". Surprisingly, the drop event is not being triggered in these drop zones; however, they ...

Troubleshooting: Resolving issues with Vue's global EventBus in my project

I am using Vue.js within a Laravel project and I am encountering an issue with the global event bus. I have created an event-bus.js file and imported it where needed. Although events are being generated upon clicking, there seems to be no reactions from th ...

Implement a function to delete an item from an array within a React object by utilizing the UseState hook

I am facing a challenge in React as I attempt to remove an element from an array within an array of objects using the UseState hook. Despite my efforts, the interface does not re-render and the object remains in place. From what I understand, in order for ...

In Pure JavaScript, an HTML element is added every time the click event is triggered

Hey everyone, I'm facing a small issue and I could use some help fixing it. I need to implement an onclick event that adds HTML code every time it's clicked. I am hesitant to use innerHTML due to its potential risks. Here is the code snippet: bu ...

The AWS Lambda function in Node.js encountered an internal server error

I've been experimenting with AWS Lambda functions, Axios, and Cheerio in a demo project. However, when I call the endpoint, I receive an error message saying {message: Internal Server Error} exports.lambdaHandler = async (event, context) => { ...

Success Notification in ASP.net MVC after Form Submission

I am looking to implement a success alert pop-up or message after the form is submitted and action is successful. In this scenario, I want to display "successfully add": Create Action : [HttpPost] [ValidateAntiForgeryToken] public ActionResult Cr ...

Locating the JSON path within an object

Need help with checking if a specific path is present in a JSON object? var data = { "schemaOne": { "name": "abc", "Path": "i.abc", "count": 5347, "subFolders": [ ] }, "schemaTwo": { "name": "cde", "Path": "i.cde", " ...

What causes the image to not appear at the center bottom of the page when using IE for loading?

Why does the loading image not appear at the center bottom of the page in IE? This function loads content when the page is loaded and also loads content when scrolled to the bottom. When you load the page index.php, you will see the loading image at the ...

Dynamic Formatting with Vue JS: Enhancing Phone Number Input

I am working on a form that includes a phone number input field, and I want the formatting of the number to change to a standard telephone number format as the user types. Can someone provide guidance on how this can be achieved using JavaScript and Vue 3? ...

Suggestions for incrementing a button's ID every time it is clicked

I am working on a button functionality that increases the button id when clicked. Below is the HTML code for the button: <input type="button" id="repeataddon-1" name="repeataddon" class="repeataddon" value="add" > Accompanied by the following scr ...

Vue unit test failures due to component method calling this.$route.query - Error: Unable to access property 'query' of null

After being a long-time consumer of the knowledge shared on StackOverflow both during and outside work hours, I've finally reached a new milestone: posting my first question here. The challenge I'm facing involves writing unit tests for a comple ...

Steps to retrieve values from a grid and execute a sum operation using PROTRACTOR

Embarking on my Protractor and Javascript journey, I am faced with the challenge of writing a test script to retrieve values of various accounts under the header "Revenue" (as shown in the image below). My task involves extracting all number values listed ...