Ways to extract the value from a v-for loop within a <select> and <option> element

Currently seeking assistance in extracting a value from a v-for loop. Can someone provide guidance on this matter? Below is the code I am working with:

Select Country:
        <select @change="selectCountryStats(country.code)">
            <option
                v-for="country in everyCountry"
                :key="country.name"
                value="country.name"
                
            >
                {{ country.name }}
            </option>
        </select>

My goal is to capture the value of country.code within the @change event, however this value is not available until the v-for loop is executed.

If anyone has a solution to this dilemma, I would greatly appreciate it.

Answer №1

The iterator of v-for cannot be used outside of the loop as it is out of scope.

To ensure that the change event handler receives the country code, you must update the binding from country.name to country.code within the <option>.value:

<option :value="country.code">

When using inline event handlers, the event parameter can be accessed through a special variable called $event. In the case of the change event targeting the <select>, you can access the new value (the country code) in the change event handler using $event.target.value:

<select @change="selectCountryStats($event.target.value)">

new Vue({
  el: '#app',
  data: () => ({
    everyCountry: [
      {
        name: 'United States',
        code: 'US'
      },
      {
        name: 'Canada',
        code: 'CA'
      },
    ]
  }),
  methods: {
    selectCountryStats(e) {
      console.log(e)
    }
  }
})
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2d5b58486d1f031b031c1f">[email protected]</a>/dist/vue.min.js"></script>

<div id="app">
  <select @change="selectCountryStats($event.target.value)">
    <option
            v-for="country in everyCountry"
            :key="country.name"
            :value="country.code"

            >
      {{ country.name }}
    </option>
  </select>
</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

Rearranging divs in Bootstrap according to the visibility of other divs

My goal is to adjust the position of a div based on the visibility of other divs. When the screen size is reduced, the divs stack up and hiding/showing any div automatically makes the stacked up divs show/hide without leaving any blank space, but this beha ...

Adjust the database table when a session expires in PHP

Within my PHP code, there is a session timeout feature that triggers after 60 minutes of inactivity. This code snippet resides in the file /mno.php, where both the login and logout functionalities are also implemented. /mno.php if (isset($_SESSION[' ...

The Vuex action is unable to execute a mutation

I am currently working on implementing an authentication feature for a website using Firebase. Whenever a user logs into Firebase, my store's action is triggered, which in turn commits a mutation to set the state with the userID. However, I keep encou ...

Wrap the chosen text within tags in a particular element

Is there a way to wrap <span> tags around selected text within an element? For instance, if someone highlights the word "John", I would like to enclose it with span tags. Sample Code in HTML <p>My name is Jimmy John, and I hate sandwiches. M ...

Experiencing inconsistent results with ticket seller kata evaluations

I'm working on improving my javascript testing skills through katas. I am facing some challenges with a specific one that involves creating a TicketClerk object to handle movie ticket transactions. ticketClark.js var TicketClerk = function() { thi ...

"Utilize Three.js to construct walls that intersect at right angles in a

Is it feasible to generate 3D perpendicular walls using Three.js like the ones shown in this image? I attempted to use THREE.Shape to sketch a rectangle, but I'm unsure how to incorporate additional perpendicular or parallel rectangles. ...

JavaScript generates a series of checkboxes dynamically, all lined up in a single row

I am currently working on a script where I iterate over objects and aim to display the text of each object on a new line in the list format, along with a checkbox next to it. Despite successfully printing everything with a checkbox, the issue I am facing i ...

An error occurred due to a class being instantiated within a module, resulting in an overflow of the

On line 7, the console.log statement prints out correctly. host.js "use strict"; var engine = require('./engine.js'); var base = require('./base.js'); var player = new base.Avatar(); console.log(player.x); class PillarGame extends ...

Is there a way to use regex to selectively color JSON keys?

My goal in JavaScript is to extract all of the JSON keys using regular expressions. I am assuming that the JSON data will be formatted with each key-value pair on a new line, like this: { "name": "Jane", "age": 30, } In simple terms, I am looking ...

The absence of a key is causing an issue - deletion cannot be completed

I need assistance with removing a question after it has been answered, but I am encountering an error message stating that my key is undefined. Error: DELETE http://api/Remove/undefined 400 (Bad Request) state={ qBank:[{id=1,question:'dd',answers ...

Switch up the animation based on the state in AngularJS

In my AngularJS application, I have implemented CSS animations for transitioning between states. The animations involve sliding content from left to right with specific timings and transforms. .content.ng-enter, .content.ng-leave { -webkit-animation-t ...

The Vue.js v-for directive seems to be malfunctioning when receiving an array from the Laravel backend

I'm having trouble understanding why the v-for directive isn't working when I pass an array through props. The only difference I notice between passing data from props and writing it directly is that there are no spaces in the passed props. I am ...

I am having trouble getting the auto refresh feature in the div to work properly

As a newcomer to PHP and Javascript, I am trying to create a div that contains an ads script and refreshes every minute. I believe I have everything set up correctly in my code: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/ lib ...

Guide to organizing a JavaScript object using a parent-child tree structure

Below is the JavaScript Object structure that I currently have: [ [ null, "A" ], [ "A", "B" ], [ "A", "C" ], [ null, "D" ], [ "D", "E" ], [ "D ...

Encountering an issue with Invariant Violation when attempting to retrieve a frame that is outside of the specified

I have created a VenueList component for my React Native app. I want to utilize the FlatList component to display a list of venues, but I keep encountering an error message that says "Invariant Violation tried to get frame out of range index" (refer to the ...

What causes the JavaScript Object to have a unique structure when it is passed as a prop?

In my React App.js file, I have a state with the following structure: state = { A: "Some text.", B: { C: "Some extra text." } } I am trying to display the value of C within a component called Header. Here is how I p ...

Ensure Website Accessibility by Implementing Minimum Resolution Requirements

Is it possible to create a website that only opens on screens with a resolution of at least 1024 x 768, and displays an error message on unsupported resolutions? I've tried using JavaScript to achieve this, but haven't had any success. Any assis ...

The $().bind function will not function properly unless the document is fully loaded

Do I need to include $(document).ready() with $().bind? Here is the HTML portion: <head> <script type="text/javascript" src="jquery-1.10.2.min.js"></script> <script type="text/javascript" src=&quo ...

Looking to extract data from a Json object and add it into a table

<!DOCTYPE html> <html> <head> <script type="text/javascript"> function displayJsonData() { var jsonData = { "cars": [ '{"model":"Sentra", "doors":4, "features":["hi"," ...

Ensuring React's setupProxy functions properly in conjunction with express.js

I've encountered an issue while trying to pass images from express to react. My express.static is correctly set up, so when I visit localhost:5000/public/images/me.jpeg, the image loads in my browser. However, when I attempt to use <img src="/publi ...