Guide to appending the chosen item from a search bar to a fresh array using vue3 js

Does anyone know how to resolve the issue I'm facing with adding selected items from a dropdown list to a new array and displaying them on the page? Currently, I have added an onblur event to the input field to hide the dropdown when clicked outside, but this has caused a problem where I am unable to select items as they are positioned outside the input area. I attempted to use @click.stop to stop propagation, but unfortunately it did not work. As a result, I am now unable to select items and add them to the selected array.

<template>
  <input
    type="text"
    v-model="input"
    placeholder="Search fruits..."
    @blur="optionsVisible = false"
    @input="optionsVisible = true"
  />
  <div
    class="item fruit"
    v-if="optionsVisible"
    v-for="fruit in filteredList()"
    :key="fruit"
    @click.stop=""
  >
    <p @click="select">{{ fruit }}</p>
  </div>
  <div class="item error" v-if="input && !filteredList().length">
    <p>No results found!</p>
  </div>
  <div class="selected">Selected: {{ selected }}</div>
</template>

<script setup>
import { ref } from 'vue';
let input = ref('');
let optionsVisible = ref(false);
let selected = ref([]);    // fill this array with selected items from the dropdown
let select = (e) => {
  selected.push(e);
};
const fruits = ['apple', 'banana', 'orange'];
function filteredList() {
  return fruits.filter((fruit) =>
    fruit.toLowerCase().includes(input.value.toLowerCase())
  );
}
</script>

I added an onblur event to the input field to hide the dropdown when clicking outside, but now I'm having trouble selecting items that are outside the input area. I tried using @click.stop to prevent propagation, but it didn't work. Now, I'm unable to select items and add them to the selected array.

Answer №1

There is an issue with the @blur directive that can be resolved by wrapping your input and fruit list div in another div. For example:

  <div @blur="optionsVisible = false">
    <input
      type="text"
      v-model="input"
      placeholder="Search fruits..."
      @input="optionsVisible = true"
    />
    <div
      class="item fruit"
      v-if="optionsVisible"
      v-for="fruit in filteredList()"
      :key="fruit"
    >
      <p @click="select">{{ fruit }}</p>
    </div>
  </div>

If you simply wish to add the name of the fruit to the selected[] array, your function should be structured like this:

<script setup>
import { ref } from "vue";

let selected = ref([]); // const is preferable

const select = (e) => {
  selected.value.push(e.srcElement.textContent);
}; // const should be used here
</script>

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

Manipulate md-select options with Angular using setValue

My goal is to update a select option, but I'm having trouble getting it to work properly. When I use this.eventForm.controls.venue.setValue(event.venue.name);, the value of venue changes to match event.venue.name. However, the select option itself doe ...

Utilize the scrollIntoView method within a jQuery function

My current setup involves using JQuery's show and hide function. Essentially, when an image is clicked, it triggers the display of an information log. The issue I am facing is that this log opens at the top of the page, whereas I would like it to scro ...

What is the process for building a JSON-formatted dictionary?

My intention is to structure my data in a way that can be accessed using a specific key. The current arrangement looks like this: const dict = []; dict.push({"student": "Brian", "id":"01", "grade":& ...

Sending JSON data results

I received this JSON response: {"data":[{"series":{"id":"15404","series_code":"TOS","publisher_id":"280","series_short_name":"Tales of Suspense","start_year":"1959","end_year":"1968","published":"1959-1968","type_id":"1","no_issues":"99","published_ ...

Issue with background image resizing when touched on mobile Chrome due to background-size property set to cover

My current challenge involves setting a background image for a mobile page using a new image specifically designed for mobile devices. The image is set with the property background-size: cover, and it works perfectly on all platforms except for mobile Chro ...

Using Vue.js causes an issue with Array.from(Object).forEach

When using vue.js 2 CLI, I typically define object data like this within the data() function: data(){ return{ user: { user_mail: '', user_password: '', user_confirm_password : '' ...

"Combining multiple DIVs into a single DIV with jQuery - a step-by-step guide

I have multiple DIVs with the same class, and I am looking to group them into a single DIV using either jQuery or pure JS. <div class="a"> <div>1</div> </div> <div class="a"> <div>2</div> ...

Differences between ClosureFeedbackCellArray and FeedbackVector in the V8 engine

Can you explain the distinction between ClosureFeedbackCellArray and FeedbackVector within V8? What steps are necessary to initiate the shift from ClosureFeedbackCellArray to FeedbackVector? What is the significance of the InterruptBudget attribute found ...

Step-by-step guide to making a personalized mesh in Babylon.js

Currently, I am utilizing the Babylonjs 3D WebGL library and finding it to be a fantastic tool. However, I am facing a challenge in replicating a feature that exists in the THREE.JS library. My scenario involves 2D polygons stored in a database. I retriev ...

HTML5Up! Skyrocketing with Meteor showers

While attempting to utilize a responsive site template from , I encountered several issues. To test the template, I downloaded the Striped package and created a clients folder in a Meteorite app where I placed the Striped folder. In order to make it work, ...

Iterating through a JSON object and an array

I've been attempting to iterate through a JSON object but I'm struggling with it. Below is the JSON object I need to work with. This JSON data will be fetched from another website, and my goal is to loop through it to extract certain details. ...

Adding a modified (id) content inline template element to another element: A step-by-step guide

In the given scenario, I am looking to achieve a function where each time the add button is clicked, the content within the template div should be appended to the element with the landingzone class. Additionally, it is important that the NEWID changes for ...

Combine arrays using underscore or lodash

Hello, I need some assistance. I have a couple of arrays containing grades with associated classes attributes like the examples below: var arr1 = [{ "id": 53, "name": "Grade 1 AppMonkeyzTest", "classes": [{ "id": 5 ...

Some CSS features might not work properly when using Vuetify alongside Vue.js and Webpack

I believe the issue may stem from my inability to correctly import the JS file for Vuetify, but I haven't been able to pinpoint any errors. It seems that certain CSS functionalities of Vuetify, like list highlight events, are not working in my applica ...

Parsing JSON data received through a URL using Ruby

When attempting to send a JSON object from JavaScript to Ruby, I am encountering issues with parsing it in Ruby. Despite trying various methods and conducting extensive research, I have not been able to find a solution. It is important to note that I am r ...

When you click on a sublevel in the vertical CSS and JavaScript onclick menu, it disappears automatically

I'm a beginner when it comes to Javascript, and I'm still getting the hang of CSS/HTML. Currently, I am working on creating a vertical menu using CSS and javascript. My goal is to have the sublevels appear on the right side of the menu when someo ...

Directive unable to recognize ng-pattern functionality

I am attempting to encapsulate an <input> within a directive in order to manage date validation, conversion from string to Date object, and keep the Date version in the original scope. The functionality seems to be working as intended. However, the n ...

Vue.js encountered an error: Module not found: Unable to resolve

My goal is to eventually create an open source template, but for now I am practicing with the MEVN stack without using Vue CLI and configuring webpack manually. However, I've encountered an error at this point. ERROR in ./src/app/main.js Module not f ...

Adding additional elements to a div in a horizontal orientation

I am currently working on a project where I need to display bars and restaurants based on specific filter criteria. I have a container div called .resultsContainer where all the results will be displayed. While I can easily append more divs (.barContainer) ...

Tips for creating a scale animation using HTML5 Canvas

I am currently developing a canvas whiteboard tool and I have reached the stage where I am focusing on implementing the Zoom In and Zoom Out feature. While the functionality is working fine, I would like to enhance it with smooth animations for scaling. H ...