How can I trigger an event in Vue.js when a selection is made in a dropdown menu?

Here is an illustration fiddle:

https://jsfiddle.net/40fxcuqd/

Initially, it shows the name "Carl"

If I choose Carol, Clara, etc., an event will be triggered and data will be logged to the console.

However, if I click on the dropdown and select "Carl" again, no event will be triggered, and nothing will be displayed in the console.

The event listener being used is @input:

<select v-model="selectedPerson" @input="myEvent()">

How can I ensure that an event is fired every time a selection is made, even if it's the same value?

Edit:

To clarify, when "Carl" is initially selected:

https://i.sstatic.net/qIqYU.png

and then the dropdown is opened:

https://i.sstatic.net/2qUbT.png

and Carl is selected once more, I would like an event to be triggered and information logged to the console. Currently, no event is triggered and nothing is printed to the console.

Answer №1

When you choose the default option of 1 in this select menu, clicking on "Carl" will not trigger any change. To capture the value of "Carl" when clicked, you need to utilize the "@change" event and include a placeholder in the select option.

new Vue({
    el: '#app',
    template: `
        <div>
            <select v-model="selectedPerson" @change="myEvent()">
                <option :value="null" disabled hidden>Select option</option>
                <option v-for="person in people" :value="person.key" :selected="person.key == selectedPerson">{{person.name}}</option>
            </select>
        </div>
    `,
    data: {
        people: [
            {key: 1, name: "Carl"},
            {key: 2, name: "Carol"},
            {key: 3, name: "Clara"},
            {key: 4, name: "John"},
            {key: 5, name: "Jacob"},
            {key: 6, name: "Mark"},
            {key: 7, name: "Steve"}
        ],
        selectedPerson: null
    },
    methods: {
    myEvent: function() {
    console.log(this.selectedPerson);
    }
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>

Answer №2

Quite a clever solution, I've implemented @click and utilized event.detail or event.which:

new Vue({
  el: '#app',
  template: `
        <div>
            <select v-model="selectedPerson" @input="myEvent($event)" @click="myEvent($event)">
                <option v-for="person in people" :value="person.key" :selected="person.key == selectedPerson">{{person.name}}</option>
            </select>
        </div>
    `,
  data: {
    people: [{
        key: 1,
        name: "Carl"
      },
      {
        key: 2,
        name: "Carol"
      },
      {
        key: 3,
        name: "Clara"
      },
      {
        key: 4,
        name: "John"
      },
      {
        key: 5,
        name: "Jacob"
      },
      {
        key: 6,
        name: "Mark"
      },
      {
        key: 7,
        name: "Steve"
      }
    ],
    selectedPerson: 1
  },
  methods: {
    myEvent: function(e) {
      if (e.detail == 0)//if (e.which == 0)
        console.log(e.type, this.selectedPerson);
    }
  }
});
body {
  margin: 20px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.as-console-wrapper {
  height: 39px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
<div id="app"></div>

A more elegant approach using data:

new Vue({
  el: '#app',
  template: `
        <div>
            <select v-model="selectedPerson" @input="myEvent($event)" @click="myEvent($event)">
                <option v-for="person in people" :value="person.key" :selected="person.key == selectedPerson">{{person.name}}</option>
            </select>
        </div>
    `,
  data: {
    people: [{
        key: 1,
        name: "Carl"
      },
      {
        key: 2,
        name: "Carol"
      },
      {
        key: 3,
        name: "Clara"
      },
      {
        key: 4,
        name: "John"
      },
      {
        key: 5,
        name: "Jacob"
      },
      {
        key: 6,
        name: "Mark"
      },
      {
        key: 7,
        name: "Steve"
      }
    ],
    selectedPerson: 1,
    prev: 0,
    isChanged: false
  },
  methods: {
    myEvent: function(e) {
      if (e.type == "input" || (e.type == "click" && !this.isChanged && (this.prev == this.selectedPerson || this.prev == 0))) {
        this.isChanged = true;
        this.prev = 0;
      } else if (e.type == "click" && this.isChanged) {
        console.log(e.type, this.selectedPerson);
        this.prev = this.selectedPerson;
        this.isChanged = false;
      }
    }
  }
});
body {
  margin: 20px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.as-console-wrapper {
  height: 39px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
<div id="app"></div>

Answer №3

By selecting a different option in the dropdown menu, you can access the index of the people array and use it to retrieve a specific value like shown below:

    myFunction: function() {
    console.log(this.people[this.selectedPerson].name);
    }
   }

Answer №4

To work around this issue, one solution is to assign a value that is not already in use when the input field is focused. This will trigger the change event regardless of which option is selected.

<select 
    v-model="selectedPerson" 
    ref="s" 
    @focus="selectedPerson = 0" 
    @change="myEvent()"
>

Check out the example on this fiddle: https://jsfiddle.net/tne1wp3q/

However, this workaround is not perfect as the change event may be triggered multiple times with each click and if no options are selected, it could remain empty. Additional code is required to handle these scenarios.

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

When dealing with errors in fetching JSON data, consider implementing a robust error handling strategy and

Is there a way to provide a fallback JSON string in case the fetch URL fails to connect? const Response3 = await fetch(`https://example.com/match/get?_=&id=${matchlist[2].id}`) ...

Display/Hide Location Pins on the Map

Looking for some assistance, please. I'm currently working on a script to toggle the visibility of locations on a map. The main code I've been using can be found here, and my own code is displayed below: !DOCTYPE html PUBLIC "-//W3C//DTD XHTML ...

Navigating through sibling elements can be accomplished by using various methods in

Can someone help me figure out how to assign unique IDs to 6 different Div elements as I step through them? The code snippet below is not working as expected, giving all Divs the same ID. What is the correct way to accomplish this task? $('#main-slid ...

"ng2-file-uploader necessitates a browser refresh in order to function

I am currently utilizing ng2-file-upload within my Angular 10 project to allow users to upload their photos. The upload process is functioning correctly, but the issue arises when the newly uploaded photo does not automatically appear in the photo list wit ...

Utilizing the Power of AJAX in Combination with an Event Loop

I have a function that is supposed to make AJAX requests with an event loop while taking 9 inputs at the top and querying them from a database. Currently, it only logs to the console but will eventually perform more actions. However, I am encountering an ...

Encountering a timeout exception while working on an ASP.Net Core 3.0 web application with Vue in Visual Studio 2019 version 16

Recently, I embarked on the journey of learning Vue. To practice my skills, I decided to develop an ASP.Net core 3.0 web application with a client-side Vue.js integration. However, upon hosting the web app, I encountered a frustrating issue that resulted i ...

Implementing a restricted Mongoose promise loop iteration count

Currently, I am developing an online store using Node, Express, and Mongoose. In the postCheckout Controller, which is responsible for handling user purchases, I am facing an issue. When a user buys a product with a quantity of 5, the code should check i ...

Troubleshooting the encryption of XSSFWorkbook in styles.xml during the save process with Apache POI v3.16

Currently, I am using Apache POI 3.16 with Java version 1.7.0-251 (Unix). I found inspiration in an example provided by @Aniruddh Chandegra on how to create and edit a password-protected excel sheet using Apache POI 3.14 (Link here). [EDIT - Below is the ...

Were you intending to import the file firebase/app/dist/index.cjs.js?

Encountering the following error message: Error: Directory import 'C:\Users\My Name\Documents\Code\WebProjects\nextfire-app\node_modules\firebase\app' is not supported when resolving ES modules import ...

Executing javascript functions from various HTML tags

The code snippet below is what I currently have: <script src="jquery-1.10.2.min.js"></script> <script> $('#year li').click(function() { var text = $(this).text(); //alert('text is ' + text); $.post("B.php" ...

What could be causing req.body to consistently come back as an empty object?

I am struggling with req.body always returning an empty object regardless of what I try. I have experimented with: var jsonParser = bodyParser.json(); and then including jsonParser in the function -> app.post('/api/get-last-project',jsonPar ...

Receiving data from multiple sockets in Node.js with Socket.io

I recently started working with Node.js to develop an online game that acts as a server-side application. This application serves the .html and .js files to the client while managing the game's logic. I'm utilizing Socket.io for communication bet ...

Is it possible to modify the colors within a JavaScript string?

I am currently working on creating a multi-timezone clock that will be shown in a web browser in kiosk mode. The basic code was taken from and the kiosk setup from: and then customized into: However, I am struggling to change the color of each timezon ...

Assign a value to the initial column of a row if the ID is found in the array

I'm attempting to set checkboxes within a specific range. The firebase_id array needs to correspond with column B in that range. If they match, the row should be set to TRUE. However, I am encountering issues where some checkboxes are randomly checked ...

The post feature is not delivering the object as expected

I have created a Login page that is supposed to post Username and Password using Axios. I wrapped the username and password into an object as shown in the code below, but when I submit the form, I receive a "201" response. Everything seems to be working fi ...

Leverage jQuery to Retrieve Text and Modify

My Content Management System automatically generates a time stamp for when a page was last updated. However, the format it provides is not ideal for my needs. I would like the date to be displayed in the US Standard way - May 24, 2013, without including th ...

Demonstrating the transformation of child elements into parent elements through angular 6 ngFor

I have a JSON array dataset where each object may contain nested arrays. In order to display the inner nested array elements as part of the parent array using Angular's NgFor, I need to format the input like this: [{ 'id': 1, 'tit ...

Is it possible to consolidate geometry in each frame during the rendering process using three.js?

Having recently delved into three.js, I've been experimenting with some concepts. My current challenge involves creating a line in the scene and using it as a reference for cloning and transforming. The goal is to display the cloned lines in a sequent ...

Using AngularJS to handle form data without ng-model

I am facing a unique situation that may seem a bit strange. I have a form that needs to edit/update information from different objects, such as services. My goal is to use ng-model to link input fields to their respective objects, but when the form is sub ...

Preparing user context prior to executing controllers within AngularJS

I recently created an AngularJS application and integrated a REST API to fetch resources for the app. As part of the authentication process, I store the user's access token in a cookie. When the user reloads the page, I need to retrieve user informati ...