Various outcomes were calculated for multiple Vue.js inputs

I am facing an issue with multiple dynamically added search forms on my webpage. Currently, when a user performs a search on one form, all inputs are being searched instead of just the relevant one.

Below is the HTML Code for reference:

<div class="row p-5">
    <input type="text" id="p1" placeholder="Enter ..." class="form-control" v-model="filter">
    <div class="result-section">
        <div class="user-list" v-for="user in filterUsers">
            <div class="label">{{user}}</div>
        </div>
    </div>
</div>
<div class="row p-5">
    <input type="text" id="p2" placeholder="Enter ..." class="form-control" v-model="filter">
    <div class="result-section">
        <div class="user-list" v-for="user in filterUsers">
            <div class="label">{{user}}</div>
        </div>
    </div>
</div>


<div class="row p-5">
    <input type="text" id="p3" placeholder="Enter ..." class="form-control" v-model="filter">
    <div class="result-section">
        <div class="user-list" v-for="user in filterUsers">
            <div class="label">{{user}}</div>
        </div>
    </div>
</div>

Here is the JS code snippet:

let app =   new Vue({
    el:"#app",
    data:{
    filter: '',
    userList : ['user1','user2','user3','user4','user5']
    },
     computed: {
        filterUsers()
        {

            var filtered = this.userList.filter((user) => {
              return user.toLowerCase().includes(this.filter.toLowerCase());
            });
            return filtered;
        },
     }

I am wondering if it is possible to have different results displayed for each input field?

Answer №1

You have been utilizing the same variable to filter each input, resulting in the filtered list being identical for all inputs. To remedy this, it is recommended that you declare separate variables, perhaps utilizing an array structure.

let app =   new Vue({
    el:"#app",
    data:{
      filter: ['', '', ''],
      userList : ['user1','user2','user3','user4','user5']
    },
    computed: {
      filterUsers()
      {
          return this.filter.map(f => {
            return this.userList.filter(user => {
              return user.toLowerCase().includes(f && f.toLowerCase())
            });
          });
      },
   },
   methods: {
      setFilterArray(value, index) {
        this.$set(this.filter, index, value);
      }
   }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div class="row p-5">
    <input type="text" id="p1" placeholder="Enter ..." class="form-control" :value="filter[0]" @input="setFilterArray($event.target.value, 0)">
    <div class="result-section">
        <div class="user-list" v-for="user in filterUsers[0]">
            <div class="label">{{user}}</div>
        </div>
    </div>
</div>
<div class="row p-5">
    <input type="text" id="p2" placeholder="Enter ..." class="form-control" :value="filter[1]" @input="setFilterArray($event.target.value, 1)">
    <div class="result-section">
        <div class="user-list" v-for="user in filterUsers[1]">
            <div class="label">{{user}}</div>
        </div>
    </div>
</div>


<div class="row p-5">
    <input type="text" id="p3" placeholder="Enter ..." class="form-control" :value="filter[2]" @input="setFilterArray($event.target.value, 2)">
    <div class="result-section">
        <div class="user-list" v-for="user in filterUsers[2]">
            <div class="label">{{user}}</div>
        </div>
    </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

Changing the element tag and flipping escape characters in html entities

My control over the string source is limited, as I can only use html(). However, I am in need of cleaning up the chaos within the source, The goal is to remove all instances of <div class="page"></div>, while retaining its content. The challen ...

What are the steps to ensure the equalizer start button functions properly?

I have created an application that mimics the functionality of an equalizer by displaying changes in audio frequencies. Issues with animation arise when you click the "Start" button again. The animation resets and begins from the start. This can be pr ...

"Improvements required for the search and filter functionality in the JSON

My JSON function retrieves image data and displays it in panels. Here is an example of the code: $.getJSON('iproducts.json',function(products){ var output = ""; $.each(products.appleitems, function(i, product) { output += "<di ...

A guide on implementing a TypoError in Node.Js and Discord.Js for enabling a bot to enter a voice channel

Hello there, I'm currently working on a music Bot for Discord using Javascript with Node.Js and I've encountered an issue: This problem arises specifically with the "play" command, but it seems to occur with all commands that involve joining a v ...

Set the cookie to expire in 5 minutes using PHP, JavaScript, or jQuery

Is there a way to set a cookie in PHP that expires in 5 minutes? I am comfortable with the setcookie() function, but unsure about how to set the expiration time. Any explanation would be greatly appreciated. Could someone please guide me on how to achieve ...

Executing javascript href using Python in Selenium

Currently, I am attempting to use Selenium in Python to click on a href JavaScript link. The HTML code appears as follows: HTML Example and my goal is to click on javascript:goType(1). This is the approach I have taken: advance_search = browser.find_el ...

Tips for aggregating the values of object arrays in React props

I need help sorting three top-rated posts. Currently, the function displays three post titles along with their ratings, but they are not sorted by best rating. Can anyone assist me with this issue? {posts.slice(0, 3).sort((a, b) => ...

Perform a series of database queries one after the other, ensuring they are completed before

Although the database queries themselves are working fine, I am facing an issue with executing them sequentially in Node. Here is an example of the queries I need to execute in order: DELETE FROM myTable; INSERT INTO myTable(c1, c2, c3) VALUES (x, y, z); ...

What is the best way to manage the "checked" state of an input checkbox using React?

I'm currently developing an application that features a form with radio buttons. One of the radio button options can be toggled on/off using a checkbox, but I want to ensure that the checkbox is disabled if the corresponding radio button is not selec ...

There is a lack of 'Access-Control-Allow-Origin' header, resulting in no access to the API

Having some trouble with the UK Parliament API, I keep encountering this error: XMLHttpRequest cannot load . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://example.com' is therefore not a ...

Verify whether an image is present without actually displaying it

I am currently integrating a script for hover-functionality: function VerifyImage(url) { var httpRequest = new XMLHttpRequest(); httpRequest.open('HEAD', url, false); httpRequest.send(); return httpRequest.status != 404; } The c ...

Is there a way to run only one instance of puppeteer.launch() and simply forward pages to it in Node.js?

I have a concern regarding the code snippet below. It appears to be launching the browser on every request, potentially causing server issues on Heroku. I would like to modify it so that puppeteer is launched as a Singleton instance, where it only needs ...

Is it not possible to make updates while the state is already in transition?

this.state = { filterData: [{ attribute: '-1', filter: '-1', value: '' }], } _createFilterUI(dataSourceColumns) { if (this.state.dataSourceIndex == -1) return <div > Kindly first select Data Sourc ...

Extracting IDs, classes, and elements from a DOM node and converting it into a string format

Can someone please guide me on how to extract the DOM tree string from an element? Let's consider this HTML structure: <div> <ul id="unordered"> <li class="list item">Some Content</li> </u ...

JavaScript file encountering a problem with its global variables

What is causing the alert("2") to pop up first instead of it being second? Why am I encountering difficulty creating global variables c and ctx? Is there a way for me to successfully create these two global variables in order to utilize ...

Using for loops in Vue.js to dynamically generate HTML elements

I have a JSON object passed into an EJS template, and I want to achieve the same table structure in VUE.js. However, it seems like v-for in Vue only works with li tags. Is there a way to create a similar loop in VUE that generates HTML elements like show ...

Is there a way to identify the top five elements that are most frequently occurring in the array?

I've successfully found the element that appears the most in an array, but now I'm facing a new challenge where I need to identify the top 5 elements that appear most frequently. Here is the array: [ "fuji", "acros", &q ...

Issue with vue-cli loader not functioning properly when utilizing default initialization for webpack-simple

Currently, I am in the process of learning Vue.JS. After installing the CLI and setting up a new project with the following commands: $ npm install -g vue-cli $ vue init webpack-simple vue-example $ cd vue-example $ npm install $ npm run dev # this is wh ...

Hidden Document Scroll Offset

When CSS is used to hide scrollbar html, body { width: 100%; overflow-x: hidden } The above code snippet removes the scroll from the window but triggers it on the body element. To calculate the scroll values in such cases, you can use: pageOffset = ...

Can information be saved to a JSON file without using a server-side language?

Previously, I've come across questions where the recommended solution involves using a server-side language. However, since I don't have knowledge of a server-side language yet, I was curious to know if it's possible to achieve this with my ...