Accessing the selected list item from an unordered list in Vue.js

How can I capture the selected item from a dropdown-style list and perform operations based on that selection?

In my list, each item is associated with a key for unique identification, except for 'Create New Filter'.

I am seeking guidance on how to determine if 'Create new filter' is clicked or if another item in the list is selected.

Here is the code snippet:

 <ul>
     <li v-on:click="create">Create New</li>
     <li v-for="item in list" :key="item.id" v-on:click="Change(item.id,item.text)">{{ item.text }}</li>
</ul>

Answer №1

From my perspective, I believe that the current approach may not be ideal. It's worth considering why the dropdown is being constructed using <ul> and <li> instead of utilizing the select element, which is specifically designed for form elements and offers a more efficient way to obtain the selected option value through the use of the v-model directive.

Nevertheless, I have followed your requirements and have devised a solution.

var app = new Vue({
  el: '.dropdown',
  data: {
    list: [{
      id: 1,
      text: 'First Filter'
    }, {
      id: 2,
      text: 'First Filter 2021'
    }, {
      id: 3,
      text: 'Full Filter'
    }],
    selectedListItem: null
  },
  methods: {
    create() {
      console.log('New filter Create Called');
    },
    getSelected (item) {
      this.selectedListItem = item;
    },
    save() {
      if (this.selectedListItem) {
        console.log(this.selectedListItem);
      } else {
        console.log('No list option selected');
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<div class="dropdown">
  <input type="text" placeholder="Select Filter" class="dropdown-toggle" data-toggle="dropdown"/>
  <ul class="dropdown-menu">
    <li v-on:click="create">Create New</li>
    <li v-for="item in list" :key="item.id" v-on:click="getSelected(item)">{{ item.text }}</li>
  </ul>
  <button @click="save">SAVE</button>
</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

Cannot adjust expiration date of express-session in browser

In my current project, I am utilizing express-session. Let's say a session has been created between the web browser and the Node.js server with a default expiration time of one hour. At this point, there is a cookie named connect.sid stored in the use ...

The JQuery function fails to execute following a successful Ajax request

I recently ran into an issue with my Ajax call. Here's the code snippet in question: $("#start-upload-btn").click(function(){ $.ajax({ type: "post", url: "", data: { newProjectName: $('#project-name') ...

How to hide the header on a specific page using Angular

Currently, I am working on an Angular project and my requirement is to hide the header block specifically on the login page. Despite attempting to hide the header on the login page, it seems that my efforts have been unsuccessful so far. Is there anyone wh ...

Scroll upwards within a nested div

Is there a way to smoothly animate the content of the inner div upward without requiring any button clicks? Also, is there a method to trigger an event once the animation has completed? ...

Exploring the retrieval of stored information from $localStorage within an AngularJS framework

I have been working on a MEAN app, and after a user successfully logs in, I want to save the returned user data in the localStorage of the browser for future use. I am using the ngStorage module for this purpose. Below is the code snippet from my LoginCont ...

Ways to retrieve object in Javascript

I retrieved this data object from a JSON file source. { "Apple": "Red", "Orange": "Orange", "Guava": "Green", } Afterward, I transformed it into an Object using: var data = JSON.parse(dataFromJson); which resulted in a JavaScript object ...

Ways to extract values from a javascript hash map by exclusively incorporating an array

So here's the issue I'm encountering. Let's consider the following scenario: let surfaces: Map<any, any> = new Map([{"83.1" => Object}, {"84.1" => Object}]) let arr1 = ["83.1"] This is the desired o ...

Issue with accessing form in Angular 6 Reactive forms for custom validator functionality

I am facing an issue with creating a password validation for reactive forms in Angular. Every time I try to verify the password, I get a “Cannot read property 'get' of undefined” error in the console. I have tried different methods to access ...

Error occurs in console when using .getJSON with undefined JSON, but does not happen when using embedded data

Can someone help me understand why I'm getting an 'undefined' response when I use console.log(tooltipValues), but there's no issue with console.log(tooltipJSON). I've noticed that when I embed the data directly in my JS code, ever ...

Modifying the content in one form field based on the information entered in another input field

I have a scheduling application that includes a form for selecting both the departure city and arrival city. The app is designed for international travel only, so when a user selects a city from Hungary as the departure city, I want to exclude all Hungaria ...

"Having trouble implementing sorting functionality on a click event in a React application with Material-UI table

Default behavior displays data in ascending order. Clicking on the table header should toggle between descending and ascending orders. Load Data in ascending order -> On click, change to descending order -> Again on click, change to ascending -> loop cont ...

How come jQuery is retaining the original DOM element classes even after I have modified them using jQuery?

Here is the code snippet I am working on: $(".drop-down-arrow-open i").click(function(){ console.log("The click function for .drop-down-arrow-open is triggered even when it is closed"); let thisParent = $(this).closest(".projects-container").find(".need ...

What can I do to comprehend and diagnose the error that is appearing in my reactjs code?

Working on a React project, I came across an error in the Google Chrome console. Uncaught true https://i.stack.imgur.com/dL8jW.png https://i.stack.imgur.com/kXn9m.png https://i.stack.imgur.com/UMQbh.png The throw true appears to be causing this uncau ...

Employing require.js, one can integrate a distinctive form of non-concatenated dat.gui source. This allows for the seamless

Excuse the SEO-friendly title, but I want to ensure that everyone can access the issue I'm currently working on. For those interested in customizing the appearance of dat.gui, you will need to download the source and include it using require.js follow ...

Receiving the latest global variable in JavaScript using jQuery

I keep receiving undefined type for: $(".ui-slider-handle").attr("title", '"'+current+'"'); Even though I can successfully alert the updated value of current on line 29, it seems to not be working with .at ...

Experiencing a 404 ERROR while attempting to submit an API POST request for a Hubspot form within a Next.js application

Currently, I am in the process of developing a Hubspot email submission form using nextjs and typescript. However, I am encountering a couple of errors that I need help with. The first error pertains to my 'response' constant, which is declared b ...

Can you explain how to create a function in Angular that accepts a number as an argument and then returns the square of that number?

I am working with an array of numbers and I want to show each number in the list along with its square value. To do this, I need to create a function that takes a number as input and returns its square as output. Here is what I have attempted so far: co ...

Embed a script into an iframe from a separate domain

While experimenting, I attempted to inject a script inside an iframe element using the following method. However, since the child and parent elements do not belong to the same domain (and I am aware that XSS is prevented in modern browsers), I was wonder ...

A different approach for dynamically displaying React components sourced from an API

As I develop a website using Next.js/React that pulls in content from Strapi CMS, my goal is to create a dynamic page template for news articles. The aim is to empower content editors by giving them the flexibility to choose the type of content they wish t ...

Transitioning from AngularJS to Angular 2: Exploring Alternatives to $rootScope.$on

Our journey with the AngularJS project has begun on the path towards the modern Angular. The ngMigration utility advised me to eliminate all dependencies on $rootScope since Angular does not have a concept similar to $rootScope. While this is straightforw ...