Filter Vue.js dropdown by checking if a word is present in the array (partial match only)

https://jsfiddle.net/75f3c2po/

Is there a way to modify the Vue.js code above so that it filters by dropdown to match the entire array even if there are commas separating other words? Currently, it only matches if the type: BMW, but I would like it to also display cards that have something like type: BMW, Ford.

Additionally, as a beginner in Vue, I was wondering if someone could show me how to update it instantly when a select option is chosen without needing to press the "search" button?

Thank you very much.

Answer №1

If you want to search by type, one way is to split the type string by a comma and then check if the array includes the specified value:

      this.searchResults = this.items.filter(function(item) {
        let isFiltered = true;
        if (filterType) {
          isFiltered = item.type.split(',').includes(filterType);
        }
        if (isFiltered) {
          if (filterCountry && filterCountry.length > 0) {
            isFiltered = item.country == filterCountry;
          }
        }
        if (isFiltered) {
          if (filterYear && filterYear.length > 0) {
            isFiltered = item.year == filterYear;
          }
        }
        return isFiltered;
      })

If you want to enable immediate searching, you can use the @change handler on your select elements:

<select v-model="selectedType" @change="search">

Answer №2

Here is a snippet that corresponds to the code in your fiddle:

I updated the searchResults property to be a computed property, ensuring it automatically updates whenever there's a change in selectedType, selectedCountry, or selectedYear.

To validate against the type, I recommend splitting your CSV list first and checking if the type exists within that array. You can achieve this by using

item.type.split(',').map(x => x.trim()).indexOf(filterType) !== -1;

It's crucial to have a strong understanding of Vue basics before diving into this. I suggest reading up on Computed Properties and Watchers

Vue.config.devtools = false;
Vue.config.productionTip = false;

new Vue({
  el: '#app',
  data: {
    selectedType: '',
    selectedCountry: '',
    selectedYear: '',
    items: [{
        name: 'Nolan',
        type: 'mercedes, ford',
        year: '2020',
        country: 'england'
      },
      {
        name: 'Edgar',
        type: 'bmw',
        year: '2020',
        country: 'belgium'
      },
      {
        name: 'John',
        type: 'bmw, audi',
        year: '2019',
        country: 'england'
      },
      {
        name: 'Axel',
        type: 'mercedes',
        year: '2020',
        country: 'england'
      }
    ],
  },
  computed: {
    searchResult: function() {
      let filterType = this.selectedType,
        filterCountry = this.selectedCountry,
        filterYear = this.selectedYear

      return this.items.filter(function(item) {
        let filtered = true
        if (filterType && filterType.length > 0) {
          filtered = item.type.split(',').map(x => x.trim()).indexOf(filterType) !== -1;
        }
        if (filtered) {
          if (filterCountry && filterCountry.length > 0) {
            filtered = item.country == filterCountry
          }
        }
        if (filtered) {
          if (filterYear && filterYear.length > 0) {
            filtered = item.year == filterYear
          }
        }
        
        return filtered;
      })
    }
  }
})
.list-item {
  margin-top: 50px;
}

.card {
  box-shadow: 0px 10px 16px rgba(0, 0, 0, 0.16);
  width: 400px;
  padding: 20px 30px;
  margin-bottom: 30px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <select v-model="selectedType">
    <option value="" disabled selected hidden>Type</option>
    <option value="mercedes">Mercedes</option>
    <option value="bmw">BMW</option>
  </select>

  <select v-model="selectedCountry">
    <option value="" disabled selected hidden>Country</option>
    <option value="belgium">Belgium</option>
    <option value="england">England</option>
  </select>

  <select v-model="selectedYear">
    <option value="" disabled selected hidden>Year</option>
    <option value="2019">2019</option>
    <option value="2020">2020</option>
  </select>

  <div class="list-item" v-for="item in searchResult">
    <div class="card">
      <p>Name: {{ item.name }}</p>
      <p>Car: {{ item.type }}</p>
      <p>Year: {{ item.year }}</p>
      <p>Country: {{ item.country }}</p>
    </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

AngularJS chatbox widget for interactive communication

Currently, I am in the process of developing the back-end for a web application utilizing angularJS. One of the key features is allowing users to communicate with each other through a pop-up chat box similar to those found in Gmail or Facebook. My goal is ...

Creating 3D Shapes with three.js

I am currently in the process of importing an STL object into my three.js scene. Unfortunately, this particular object seems to be using a large amount of GPU resources for rendering and animation, causing the overall performance of the scene to suffer. B ...

Is it possible to alter the canvas origin when using an Orthographic camera with a CSS3D

When transitioning the camera from perspective to orthographic, I noticed that the camera's position also shifts so that the coordinates 0,0,0 are situated in the top left corner. Is this expected behavior? Check out this Example for reference. Ortho ...

Passing Optional Parameters to AngularJS Modal

Is there a way to pass an optional parameter to my angularJS modal? Let's take a look at the code: TRIGGER CONTROLLER: $modal.open({ templateUrl: 'UploadPartial.html', controller: 'photos.uploadCtrl', resolve: { presele ...

`How to prevent other events from triggering in jQuery while an animation is running`

Writing again to seek help with a script issue on my webpage. I previously posted about a problem with the menu focus a week or two ago on this forum. A user suggested a helpful script, but unfortunately, it has a bug that I can't seem to fix. I' ...

The csurf token in Node.js consistently shows as invalid

Upon installing the csurf package on my Node.js Express application, I encountered an issue with validating the CSRF token. Despite properly displaying the token in the form as name="_csrf" with a hash value set using req.csrfToken(), I consistently receiv ...

What is the solution for resolving a 404 error when making a POST request using Axios in a

I am encountering a 404 error when trying to send a request to an API, and I can't find any leads in the network. Can anyone assist me with this issue? Here is my code: loginMethod() { const config = { userName: "<a href="/cdn-cgi/l/ ...

Spin Three.js camera around central point with mouse control

I am attempting to achieve camera rotation around the central point (0, 0, 0) using mouse controls. However, when rotating 180deg to the right or left, and then attempting to rotate vertically, the vertical rotation does not occur at all. My approach inv ...

Connect Promise.all() with an array of identification numbers

I'm fairly new to working with Promises and I have a question regarding linking the results of `Promises.all()` to unique IDs for each promise once they resolve. Currently, I am making requests to a remote server and retrieving data for each request. ...

Encounter a scope.router.go error when using Vue.js with System.js

During my testing of a Vue.js-System.js app before transitioning to webpack2, I encountered an issue with the routing pattern. In the OPA Memberships component, when clicking on a link, I aim to request a Registration page from the router. To achieve this ...

Does three.js have a MoveTo feature available?

As a beginner in three.js, I'm looking for a function similar to Unity's move towards in order to move objects from their current position to a specific Vector3. Any suggestions or insights on how to achieve this would be greatly appreciated. Tha ...

Having trouble sending an HTTPS request in NodeJS only to receive an HTTP response instead

As I develop my website using NodeJS and deploy it on Heroku, I encountered an issue upon opening the website. Here is the problem at hand: When looking at the main source file of my web application: app.get('/', (req, res) => { var data ...

Problem with Shopping Cart: Unable to add items to the "Shopping Cart Page". Error in setting property 'textContent' to null

I am currently immersed in the process of developing a shopping cart using HTML, CSS, and Javascript. I have been following a tutorial on Youtube, but I have encountered a glitch. Despite attempting a few solutions, I continue to encounter the following er ...

Creating a texture in Three.js using an image file

Having some difficulty with creating a texture from an image file using Three.js. Currently, attempting to create a mesh using the following function: var image = document.createElement('img'); image.src = imageFile; var texture = ne ...

Having trouble with the postcss-import grunt plugin?

Here is the layout of my project: my_project |-- css | -- main.css |-- css-dev | -- main.css |-- node_modules | -- bootstrap | -- dist | -- css | -- bootstrap.css |-- package.json `-- Gruntfile.js The contents of my Gr ...

Flashing background color appears as I scroll

Whenever a user touchstarts on a div, I want to apply a background-color to that specific div. Then, as the user scrolls, I use the $(window).scroll event to either reset or remove the background-color from all divs. However, my issue arises when a user b ...

How come I'm getting a numerical output instead of an array after using the array.push() method in this code?

In need of a custom function to append an element to the end of an array, I encountered a requirement: if this new element shares its value with any existing elements in the array, it should not be appended. For instance, adding 2 to [1,2] should result in ...

Tips for adjusting the file name and extension when saving a text file from a data URI

When I try to download data using a Data URI (this method works in Chrome and Firefox), I use the following code: url1 = "data:attachment/plain;base64,encodeuri(<base64data-xyz>)" By specifying the MIME type as attachment, it forces the file to dow ...

Issues with the functionality of Onsen UI ons-splitter-side event handlers have been reported

I have been attempting to make the postopen and postclose events function properly, but I am facing challenges in getting them to work. I have been following the guidelines provided here. The basic outline of my code looks like this: <ons-splitter va ...

Angular 2 Element Selection: Dealing with Unrendered Elements

This form consists of three input fields: <div> <input *ngIf = "showInputs" #input1 (change)="onTfChnage(input2)" type="text"/> <input *ngIf = "showInputs" #input2 (change)="onTfChnage(input3)" type="text"/> <input *ngIf = "showInp ...