Searching in Vue based on the selected option is only possible by the selected criteria and not by id, regardless of the

#1 Even if chosen, cannot search by id. The 'name' condition in the loop works well but I am unable to correctly search by id (returns nothing).

#2 When selecting an option from the dropdown menu, it only displays until I start typing. I would like it to remain displayed even while typing.

  name: 'CharactersList',
  data: function () {
    return {
      selected: '',
      searchQuery: '',
      list: [],
      page: 1
    }
  },
  computed: {
    filteredList () {
      if (this.selected === 'Charactername' && this.searchQuery) {
        return this.list.filter((item) => {
          return item.name.toLowerCase().includes(this.searchQuery)
        })
      } else if (this.selected === 'Id' && this.searchQuery) {
        return this.list.filter((item) => {
          return item.id.includes(this.searchQuery)
      })
      } else {
        return this.list
      }
    }
},
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<select v-model="selected">
      <option disabled value="" required>Search by</option>
      <option class="charactername">Name</option>
      <option class="episode">Episode</option>
      <option class="id">Id</option>
</select>
<input v-model="searchQuery" type="text" placeholder="Type here...">

<table><span class="allcharacters">All</span>
    <tr class="wrapper-top-bar">
        <td>Photo</td>
        <td>ID</td>
        <td>Name</td>
        <td>Gender</td>
        <td>Species</td>
        <td>Last episode</td>
        <td>Add to fav</td>
    </tr>
    <tr class="wrapper-list-table" v-for="item in filteredList" v-bind:key="item.id">
        <td><img v-bind:src="item.image"/></td>
        <td>{{item.id}}</td>
        <td>{{item.name}}</td>
        <td>{{item.gender}}</td>
        <td>{{item.species}}</td>
        <td>{{}}</td>
        <td><button>⭐</button></td>
    </tr>
</table>

Answer №1

Step 1: Initiated with placeholder model

data: function() {
return {
  selected: "",
  searchQuery: "",
  list: [
    {
      id: 1,
      name: "John",
      gender: "Male",
      species: "Human",
      episode: "Breaking Bad"
    },
    {
      id: 2,
      name: "Sarah",
      gender: "Female",
      species: "Alien",
      episode: "Star Trek"
    },
    {
      id: 3,
      name: "Mike",
      gender: "Male",
      species: "Robot",
      episode: "Black Mirror"
    }
  ],
  page: 1
};
},

Step 2: Transformed method restructured as follows

computed: {
filteredList() {
  if (this.searchQuery && this.selected) {
    return this.list.filter(item => {
      if (this.selected === "name" || this.selected === "episode") {
        return (
          item[this.selected] &&
          item[this.selected]
            .toLowerCase()
            .includes(this.searchQuery.toLowerCase())
        );
      } else {
        return (
          item[this.selected] &&
          item[this.selected].toString() === this.searchQuery.toString()
        );
      }
    });
  } else {
    return this.list;
  }
}
}

Step 3: Constructed HTML template shown below

<div>
  <select v-model="selected">
    <option disabled value="" required>Search by</option>
    <option value="name">Name</option>
    <option value="episode">Episode</option>
    <option value="id">Id</option>
  </select>
  <input v-model="searchQuery" type="text" placeholder="Type here...">
    <table><span class="allcharacters">All</span>
        <tr class="wrapper-top-bar">
            <td>Photo</td>
            <td>ID</td>
            <td>Name</td>
            <td>Gender</td>
            <td>Species</td>
            <td>Last episode</td>
            <td>Add to fav</td>
        </tr>
        <tr class="wrapper-list-table" v-for="item in filteredList" v-bind:key="item.id">
          <td><img v-bind:src="item.image"/></td>
          <td>{{item.id}}</td>
          <td>{{item.name}}</td>
          <td>{{item.gender}}</td>
          <td>{{item.species}}</td>
          <td>{{item.episode}}</td>
          <td><button>⭐</button></td>
        </tr>
    </table>
 </div>

DEMO

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

Creating a Vue.js webpack build optimized for production platform

This is my first experience using a frontend Build Tool. Up until now, I've only worked with frameworks that were as simple to install as adding a <script> tag to my HTML page. Now you have an idea of my skill level. I am working on a Vue.js/Vu ...

An effective way to retrieve a property from an observable by utilizing a pipe

I'm having trouble storing an OrderState object in my ngrx store and extracting data from it for my UI using the async pipe. Specifically, I want to retrieve a child property from this observable object. order.state.ts export interface OrderState { ...

Development of client and server using socket.io in node.js

I am trying to set up a basic demo using socket.io from http://socket.io The server (app.js) is functioning properly. However, I am encountering issues with the client side: <script src="/socket.io/socket.io.js"></script> <script ...

Perform an action in jQuery when a class is modified

I am trying to create an event that will trigger when a specific element receives a class, and also when that class is removed. For example: <button id="my_butt_show">showtime</button> <button id="my_butt_hide">hide me</button> &l ...

The video element in HTML5 is not showing up on Safari browsers, but it is functioning properly on Chrome

I have set up a video slider on my webpage. You can view the site The code is functioning perfectly on Chrome and iOS Safari, but there seems to be an issue on desktop browsers. When inspecting the page in Safari, the video elements are present in the HTM ...

Uncover the solution to eliminating webpack warnings associated with incorporating the winston logger by utilizing the ContextReplacementPlugin

When running webpack on a project that includes the winston package, several warnings are generated. This is because webpack automatically includes non-javascript files due to a lazy-loading mechanism in a dependency called logform. The issue arises when ...

Adding a custom class to the body element for specific routes in Next.js can be achieved by utilizing the features of

I am looking to apply my custom class to certain pages, with the exception of specific routes. For example, all pages should have the class fixed-header, except for the following routes: /cart/step-1 /login This class should be added or removed from the ...

"Allow users to select only the year with Material-UI DatePicker

Is there a method to display solely years using the Material UI DatePicker component in React? I would like to enable users to choose only the year, excluding months or days. Please note that neither the openToYearSelection option nor the autoOk feature ...

Building numerous pagination features in a single page using Codeigniter

I'm just starting out with codeigniter and I need help creating multiple paginations on one page. I've tried it, but only one pagination is working while the others are giving me errors. Can someone please assist me? I read some suggestions that ...

Having trouble viewing the value of request headers in Firebase?

Here is my code snippet: var headers = new Headers(); headers.append("bunny", "test"); headers.append("rabbit", "jump"); fetch("blahurl.com/someservice", {headers:headers}) When it comes to handling the request on Firebase: export const listener = funct ...

Is it possible to simultaneously play several one-shot sound effects on mobile web browsers?

I'm attempting to trigger a sound effect when the user clicks a button on my web application. Initially, I experimented with this approach: var sound = new Audio("soundeffect.ogg"); function clickHandler(){ sound.play(); } Unfortunately, if the ...

What is the process for saving appends to variables and converting them to PHP for storage in a database?

<html> <head> <meta charset="utf-8"> <title>Test page for Query YQL</title> <link rel="stylesheet" href="http://hail2u.github.io/css/natural.css"> <!--[if lt IE 9]><script src="http://hail2u.github.io ...

Nuxt 3 scrollBehavior doesn't pause for page completion before scrolling

My current project is developed using Nuxt3. I have a situation where there is a link on page A that directs the user to an anchor within a component on page B. The expected behavior is for the user to click the link and be smoothly scrolled to the specifi ...

AngularJS framework may encounter an issue where changes in $scope data do not reflect in the view

I have noticed that when I reload the data using my function, the view does not change. After some research, I found that adding $scope.$apply() should solve this issue. However, I am encountering an error when trying to implement this solution. https://d ...

Live notification application using node.js

I am looking to create a recipe maker webapp for practice purposes. This webapp will consist of 2 main pages: the index page and the recipes page. On the "index" page, users can create their own recipes. On the "recipes" page, users can view a table ...

Incorporate dc.js into your Cumulocity web application

Our team is facing a challenge while trying to integrate dc.js into our Cumulocity web application. While the standalone version works perfectly, we encounter issues when attempting to use it within Cumulocity. Below is the code for our standalone applica ...

What is the process of initializing divs in DataTables?

My application has a DataTable installed, but I encountered an error message stating "DataTables warning: Non-table node initialisation (DIV). For more details about this error, please visit http://datatables.net/tn/2". I'm aware that DataTables is d ...

How can I resolve the issue of Nuxt not loading an inlined SVG as a Vue component in Firefox?

I encountered an issue when trying to use SVG icons in a .vue file as a component. The icons work fine in Chrome, but I'm getting errors in Firefox and the icons are not rendering properly. The error message points to a specific icon, so I need some g ...

Interacting with react-virtualized: accessing Grid's public functions

Trying to utilize the public method recomputeGridSize on a Grid component that I am currently rendering. I have set up the ref, but when attempting to call the method, it seems like it is not accessible. Outlined below is where the ref is established with ...

Showing a database table in an HTML format using JavaScript

I am currently working on displaying a database table in HTML. I have written a PHP code snippet which retrieves the table data and formats it into an HTML table without any errors: function viewPlane() { if(!$this->DBLogin()) { $ ...