Unable to focus on the same DOM element multiple times - Vue.js

Apologies for any syntax errors, although the code is functioning perfectly. There may have been a mistake during the copying process.

Situation: I am facing an issue with a component called 'dropdown', which is repeated three times using v-for='(item, index) in search'. The 'search' array contains three objects. While the for loop and if statement within the 'filterInput' method work correctly, I am struggling to pinpoint the specific 'dropdown' element that corresponds to search[i]. My goal is to eliminate the DOM element of search[i] when the text value doesn't match the input.

<div id='app'>
  <input type='text' placeholder='Start typing here...' v-model='input'
    @click='drop()' v-on:blur='close()'>
  <ul id="dropdown" class='nodisplay'>
    <dropdown v-for='(item, index) in search' v-bind:item='item' v-   
      bind:index='index'></dropdown>
  </ul>
</div>

Vue.component('dropdown', {
  props: ['item', 'index'],
  template: `<li><a href="#"> {{item.text}}</a></li>`
})

var app = new Vue({
  el: '#app',
  data: {
  input: '', //reactive
  search: [
    {id: 1, text: 'Jacob'},
    {id: 2, text: 'Jeff'},
    {id: 3, text: 'Tom'}
  ]
  },
  methods: {
    drop: function() {
      let dropdown = document.getElementById('dropdown');
      dropdown.classList.toggle('nodisplay');
    },
    close: function() {
      let dropdown = document.getElementById('dropdown');
      dropdown.classList.toggle('nodisplay');
      document.querySelector('input').value = '';
    },
    filterInput: function(index) {
      //dropdown items in console: app.search[index].text = 'xyz'
      for (let i = 0; i < this.search.length; i++) {
        if (!(this.search[i].text.startsWith(this.input))) {
          //hide or remove this current search element from dropdown
        }
      }
    }
  },
  watch: {
    input: function() {
      this.filterInput();
    }
  }
})

In summary, I am seeking guidance on how to target

Answer №1

If you are seeking information on parent-child communication, I have provided a response earlier today here.

To achieve this, you must utilize the $emit method to trigger an event from the child component and update the value in the input field, similar to the example outlined in the documentation.

Below is the code snippet:

HTML

<div id='app'>
  <input type='text' placeholder='Start typing here...' v-model='input'
    @click='drop()' >
  <ul id="dropdown" :class="{'nodisplay': dropDownClosed}">
    <dropdown v-for='(item, index) in search' v-bind:item='item' v-   
      bind:index='index' v-on:getdropdowninput="getdropdowninput"></dropdown>
  </ul>
</div>

JS

dropdown = Vue.component('dropdown', {
  props: ['item', 'index'],
  template: `<div><li ><a @click="selectval(item.text)" href="#"> {{item.text}}</a></li></div>`,
  methods: {
     selectval (value) {
        this.$emit("getdropdowninput", value)
     }
  }
})

var app = new Vue({
  el: '#app',
  data: {
    input: '', //reactive
    dropDownClosed: false,
    search: [
      {id: 1, text: 'Jacob'},
      {id: 2, text: 'Jeff'},
      {id: 3, text: 'Tom'}
    ]
  },
  methods: {
    drop: function() {
      this.dropDownClosed = true
    },
    getdropdowninput: function(value) { 
       this.dropDownClosed = false
       this.input = value;
    },
    filterInput: function(index) {
      //dropdown items in console: app.search[index].text = 'xyz'
      for (let i = 0; i < this.search.length; i++) {
        if (!(this.search[i].text.startsWith(this.input))) {
          //hide or remove this current search element from dropdown
        }
      }
    }
  },
  watch: {
    input: function() {
      this.filterInput();
    }
  }
})

Check out the functioning fiddle.

Utilize Dynamic Classes: I have also demonstrated how to dynamically add/remove classes using the Vue approach, rather than using document.getElementById. Take note of this line:

<ul id="dropdown" :class="{'nodisplay': dropDownClosed}">

The nodisplay class will be applied when dropDownClosed variable is true and removed when it is false.

Filtering Method:

To implement filtering, consider using a computed property within the v-for loop. This way, whenever there is an input change, you can filter the search array. Here's an example:

  computed: {
     filteredInput: function(){
       if(this.input === '' || !this.input){
          return this.search
       } else {
          var self = this
          return this.search.filter(
             function( s ) {
             return s.text.indexOf( self.input ) !== -1; }
          );
       }       
     }

View the operational fiddle here.

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

The Express Validator is unable to send headers to the client once they have already been processed

I recently integrated express-validator in my Express JS project, but encountered a warning when sending invalid fields to my api: UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client This ...

Having trouble with your JavaScript regex not functioning properly?

I am currently working with an array of arrays and I need to iterate through it to retrieve each word, excluding any "@", punctuation, and hashtags. However, my regular expression seems to be removing certain words entirely from the array and I can't ...

Clicking on Rows in DataTables: Enhancing

I have been utilizing the jquery datatables plugin, and have encountered an issue with the row click functionality. Strangely, it only seems to work on the first page of the table. When I navigate to any subsequent pages, the row click fails to respond whe ...

The Process of Sending Values from app.js to a Vue File in Vue.js

My app.js is currently receiving a value called gtotal. I am trying to pass this value to the orderForm.vue file but am facing some difficulties in achieving this. require('./bootstrap'); window.Vue = require('vue'); window.EventBus ...

How to showcase an image with Angular 2?

Just starting out with Angular 2 and ran into an issue while trying to display an image using a relative path. <img src="./../images/publicVideo1.PNG"> Unfortunately, I encountered the following error: null:1 GET http://localhost:4200/null 404 (No ...

Vercel's Open Graph Image Generation encountering Failure - ERR_MODULE_NOT_FOUND

I am currently working on a project that utilizes NextJS and is deployed on Vercel. In an attempt to generate images, I am using the @vercel/og Open Graph Image generation library. However, each time the api route for the OG image is called, it leads to an ...

Restricting Entry to a NodeJS Express Route

Currently, I am in the process of developing an express project where I have set up routes to supply data to frontend controllers via ajax calls, specifically those that start with /get_data. One issue I am facing is how to secure these routes from unauth ...

What steps can I take to ensure that my popup images continue to appear?

Currently, I am working on creating a webpage that features thumbnails sourced from a local geoserver. The goal is to have these thumbnails expand into dialog windows that can be moved around. While I have successfully implemented the functionality to expa ...

Tips for centering a div horizontally when it exceeds the width of a mobile screen

My challenge is to create a circular div element that is wider than the mobile screen and perfectly centered. This circular div needs to be an exact circle, specifically targeted for mobile screens. I've attempted to achieve this using the code in th ...

When working with React.js, encountering the error message "Unexpected token export on export{default as

When attempting to import components into my newly installed app, I used the following syntax: import {Cards , Chart , CountryPicker} from '../components' I also created an index.js file with the following content: export {default as Cards} ...

What is the best way to verify the invocation of a Vuex Mutation within a Vue component?

Imagine you have a Vue component with a method structured like this: methods:{ doSomething(someParameter){ //potentially manipulate the parameter in some way this.$store.commit("storeSomething",someParameter); let someP ...

Recover files from the latest commit in Git, with files having no data inside them

Hello there! I encountered an issue with Git recently. I was attempting to clone a repository in order to push my project code, but I ran into an upstream error. I tried doing a git pull without success, then attempted to revert back to my initial commit ...

The Nuxt auth module fails to update the user's loggedin status within the store state

Currently, I am implementing Authentication functionality using the Nuxt Auth Module. My frontend is built on Nuxt Js, while my backend is running Laravel 5.7 In nuxt.config.js, I have configured the auth settings as follows: auth: { strategies: { ...

Using JavaScript to assign function arguments based on arbitrary object values

I am facing a challenge with a collection of arbitrary functions and a method that takes a function name along with an object or array of parameters to call the respective function. The issue arises from the varying number of inputs in these functions, som ...

Typescript: Shifting an image to the left and then returning it to the right

As a newcomer to Typescript, JavaScript, and front-end development, I am experimenting with creating a simulation of an AI opponent's "thinking" process when playing cards in a game. The idea is to visually represent the AI's decision-making by s ...

Deactivate fields B and C unless input A is provided

http://jsfiddle.net/6Pu3E/ JavaScript Code: $(document).ready(function() { var block = false; if ($('#password').attr('disabled')) { block = false; } else { block = true; } if (block) { $(&a ...

JavaScript code that functions similarly to VLOOKUP, allowing you to map input values from one field to

As a beginner in HTML and JavaScript, I am trying to create a simple form that automatically populates a specific "Customer Code" when a "Customer Name" is selected from a dropdown list (similar to an Excel VLOOKUP). However, the examples I found on Stack ...

Using VueJS for Dynamic Class Binding

Using Vue version 3.0.5. I have a component named Cube.vue where I am attempting to dynamically assign a blue or green class to a child element. The component has been created and imported into a specific page, however, I am facing issues getting the con ...

Receiving JSON objects from Javascript in Django Views

When I attempt to pass a Json Object value from making an API call to my views.py in Django template, I encounter difficulty retrieving the value after an ajax call. let application = JSON.parse(sessionStorage.getItem("appId")); let kycStatus = a ...