bob
bob

Reputation: 31

How to add the selected Item from a search bar to a new array vue3 js?

I'm trying to add the selected item from a dropdown list to a new array and display it on the page. I did a onblur event on input field in purpose to hide the dropdown when I click outside, but now I can't select the items ,cause they are also outside the input. So I've tryed to stop propagation via @click.stop event. And failed. So now I can't select the items and add it 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 did a onblur event on input field in purpose to hide the dropdown when I click outside, but now I can't select the items ,cause they are also outside the input. So I've tryed to stop propagation via @click.stop event. And failed. So now I can't select the items and add it to the selected array.

Upvotes: 0

Views: 172

Answers (1)

ProDeSquare
ProDeSquare

Reputation: 114

Issue with @blur directive: Wrap your input and fruit list div in a div. e.g.

  <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 just want to push the name of the fruit to the selected[] you should write your function like this:

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

let selected = ref([]); // better to use const

let select = (e) => {
  selected.value.push(e.srcElement.textContent);
}; // better if you use const
</script>

Upvotes: 0

Related Questions