Utilizing a search bar with the option to narrow down results by category

I want to develop a search page where users can enter a keyword and get a list of results, along with the option to filter by category if necessary. I have managed to make both the input field and radio buttons work separately, but not together. So, when someone performs a keyword search, those results are shown. When someone filters by category, only those results are displayed. However, I am unsure how to utilize my search box once a category is selected. I would like the search box to search within the results belonging to that specific category.

HTML

<div id="app" v-cloak>
 <div class="container">
  <div class="row search-wrapper"> 
    <div class="col-xs-6 col-md-4">
      <div class="input-group stylish-input-group">
                    <input type="text" class="form-control"  placeholder="Filter by keyword"  v-model="search">
                    <span class="input-group-addon">
                        <button type="submit">
                            <span class="glyphicon glyphicon-search"></span>
                        </button>  
                    </span>
                </div>
    </div>    
    <div class="col-xs-12 col-md-8 text-right">
      <div data-toggle="buttons">
      <label class="btn btn-sm btn-all">
        <input type="radio" v-model="selectedCategory" value="All" /> All
      </label>
      <label class="btn btn-sm btn-hr">
        <input type="radio" v-model="selectedCategory" value="HR" /> Our People
      </label>
      <label class="btn btn-sm btn-finance">
        <input type="radio" v-model="selectedCategory" value="Finance" /> Finance
      </label>
     <label class="btn btn-sm btn-other">
        <input type="radio" v-model="selectedCategory" value="Other" /> Other
      </label>
</div>
    </div>    
  </div> <!-- search wrapper -->
  <div class="row sm-padding">
    <div v-for="form in filteredForms" class="col-xs-6 col-sm-4 sm-padding">
      <div class="box">
        <div class="form-type" v-bind:class="{ compClass }"></div>
        <div  class="text-right"><span class="glyphicon glyphicon-star"></span></div> 
        <div class="box__title"> {{ form.name }} </div>
        <div class="box__subtitle"> {{ form.category }} </div>
        <div class="box__link"> <a href="#" title="">Use this form</a></div>
      </div>
    </div>
    <div v-if="filteredForms.length === 0" >
      <div class="box box__empty"> No Match Found</div>
    </div>
  </div> <!-- results --> 
 </div> <!-- container -->
</div> <!-- #app -->

Vue JS

var vm = new Vue({
  el: '#app',
  data: {
      forms: [
        { name: 'Learning and Professional Development Record', category: 'HR', activeColor: 'red', views: 312},
        { name: 'New Vendor Request', category: 'Finance', activeColor: 'blue', views: 23121 },
        { name: 'On-call allowance', category: 'HR', activeColor: 'red', views: 231},
        { name: 'Overtime Claim', category: 'HR', activeColor: 'red', views: 443},
        { name: 'Alteration of Kindergarten Enrolment', category: 'Other', activeColor: 'yellow', views: 403},
        { name: 'Adjustment to vendor details', category: 'Finance', activeColor: 'blue', views: 8843}
      ],
      selectedCategory: 'All',
      search: '',
  },
  computed: {
    filteredForms: function() {
        var vm = this;
        var category = vm.selectedCategory;

       var forms = vm.forms.filter((form) => {
       return form.name.toLowerCase().includes(vm.search.toLowerCase());
          });

      if(category === "All") {
            return forms;
        } else {
          return vm.forms.filter(function(dept) {
          return dept.category === category;
            });
    }
    }
  }
})

Pen: Codepen

Answer №1

Your filtering system within a specific category is operating on the entire list rather than the list filtered by keyword:

filteredItems: function() {
    var vm = this;
    var category = vm.selectedCategory;

    var items = vm.items.filter((item) => {
        return item.name.toLowerCase().includes(vm.search.toLowerCase());
    });

    if(category === "All") {
        return items;
    } else {
        return items.filter(function(item) {
            return item.category === category;
        });
    }
}

For further reference, here is an updated Pen link: https://codepen.io/anon/pen/rpQzpz

Answer №2

I have made an update to the computed value for you. Your forms array now undergoes filtering with just one array iteration.

const vm = new Vue({
  el: '#app',
  data: {
      forms: [
        { name: 'Learning and Professional Development Record', category: 'HR', activeColor: 'red', views: 312},
        { name: 'New Vendor Request', category: 'Finance', activeColor: 'blue', views: 23121 },
        { name: 'On-call allowance', category: 'HR', activeColor: 'red', views: 231},
        { name: 'Overtime Claim', category: 'HR', activeColor: 'red', views: 443},
        { name: 'Alteration of Kindergarten Enrolment', category: 'Other', activeColor: 'yellow', views: 403},
        { name: 'Adjustment to vendor details', category: 'Finance', activeColor: 'blue', views: 8843}
      ],
      selectedCategory: 'All',
      search: '',
  },
  computed: {
    filteredForms() {
      return this.forms.filter(dept => (dept.category === this.selectedCategory || this.selectedCategory === 'All') && dept.name.toLowerCase().includes(this.search.toLowerCase()));
    }
  }
});

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

Displaying Title and Description Dynamically on Markers in Angular Google Maps

I am currently utilizing Angular-google-maps, and here is the HTML code snippet: <ui-gmap-google-map center='mapData.map.center' zoom='mapData.map.zoom' events="mapEvents"> <ui-gmap-markers models="mapData.map.markers ...

Gain entry to the v-slot data within the script section

In an attempt to display a loading indicator within a component containing a slot element (referred to as the wrapper component), I have implemented a function in the wrapper that alters the state of the indicator based on a boolean input (setSpinnerVisibl ...

Retrieve the value of a dynamically generated radio input with Vue.js

I have a requirement to dynamically generate a list using v-for, which includes radio input elements. The purpose of this list is to allow patients to book appointments based on the selected slot value that is passed to a function when a radio button in th ...

Looking to switch up the hide/show toggle animation?

Currently, I have a functioning element with the following code. It involves an object named #obj1 that remains hidden upon page load but becomes visible when #obj2 is clicked. #obj1{ position:fixed; width:100px; bottom:180px; right:10 ...

NodeJs:- Retrieve data from the initial dropdown menu and display it dynamically in the secondary dropdown

Currently, I am working on a dropdown list and facing an issue where the results displayed in the second dropdown need to be filtered based on the selection made in the first dropdown. The EJS code snippet that I am using is: <div class="form-group"& ...

Lack of element content in AngularJS unit testing

I am currently working with AngularJS 1.5+, jasmine, and karma, and I am facing an issue when testing a component along with its template. When the component's template is compiled, it seems to be missing the expected content. Here is a snippet of th ...

When a checkbox is selected, new input fields will dynamically appear

I have a table with 3 text fields and I would like to dynamically add the same set of text fields when a checkbox is clicked. Below is the code snippet I have, how can I achieve this using PHP and JavaScript? echo "<td>Screen ".$i."</td>"; ...

What are the benefits of using default ES module properties for exporting/importing compared to named module properties?

Currently studying the Material UI documentation, I came across this statement: It is noted in the example above that we used: import RaisedButton from 'material-ui/RaisedButton'; instead of import {RaisedButton} from 'material-ui&apo ...

Guide on displaying ajax data using PHP

I'm attempting to display the user-entered data by using AJAX to transfer it and then trying to print or echo it with PHP, but I'm having trouble getting it to work. enter code here Here is my code: <html> <head> <title> ...

Enhancing the efficiency of JavaScript code

Imagine you have a web application processing 1,000,000 user logins per hour. and the code below is executed during each user login: if (DevMode) { // make an Ajax call } else if (RealMode) { // make another Ajax call } else { // Do something ...

When running npm install, the dist folder is not automatically generated

I found a helpful tutorial at this link for creating a Grafana plugin. However, when I tried copying the code from this link to my test server (without the dist/ folder) and ran npm install, it did not generate a new dist/ folder but created a node_module ...

Unusual problem encountered with Chart.js bar chart, image dispersion

On my HTML page, I have integrated a stacked bar chart using the Chart.js library to visually represent data for users. The data changes based on user selection, and the JavaScript function that enables this onclick feature is: function aggLav(){ [... ...

Locate the div element containing specific text and remove the text from the

Is there a way to locate a div that contains specific text and remove only that specific text from the div? For instance: <div> DeleteText <span>Something text</span> <div>Something span inner text </div> </div> I am l ...

Guide to creating a toggle button

Can someone help me create a button that toggles between displaying block and display none when clicked? I've been trying to use Classlist.toggle with JavaScript, but I'm not sure if I have the correct classes targeted. let showCart = documen ...

Tips for refreshing CSS following an ajax request

Currently, I am facing an issue with the CSS formatting on my page. I am using Django endless pagination to load content on page scroll. However, when new content is loaded, the CSS applied to the page does not work properly and needs to be refreshed. Can ...

The controller and node js request associated are invisible to my HTML page

Here is my HTML code. I have just created a unique controller for a specific part of the code. <div class="mdl-grid" ng-controller="ValueController"> <div class="mdl-card mdl-shadow--4dp mdl-cell--12-col"> <div class ...

Disable the setTimeout() function in order to prevent the countdown from refreshing

I have a JavaScript countdown function that is working well, but I am unsure how to stop and refresh the timer to extend the time. When I call the function again before it times out, it behaves strangely by showing two countdown timers because the updateTi ...

Is there a way for me to send a URL request from my website to a different server using PHP?

I am looking to initiate a request from my website to my server using a specific IP address. From there, I need the server to send another request to a different server and then display the response on the webpage. Can anyone provide guidance on how to ...

What is preventing this brief code from functioning properly? I am trying to extract a value from an input field and add it to a div element

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script src="//ajax.googleapis.com/ajax/libs/jque ...

Sending data from a Flask application written in Python to a JavaScript file using AJAX for seamless integration

As I am still in the learning process, please bear with me. I have been making attempts to find solutions, but often encounter issues when sending data of type="POST" from JavaScript to Flask using AJAX. This is the code snippet from my app.py f ...