Retrieve the text value of a selected option in a v-select component

After reading some documentation about v-select and slots, I am a bit confused about whether it can be applied to my specific scenario on this codepen.

All I really need is to capture the selected text (not the value) and utilize it somewhere in the code:

new Vue({
  el: "#app",
  vuetify: new Vuetify(),
  data: {
    state: {},
    selectedText: "",
    states: [
      { value: "a", text: "alpha" },
      { value: "b", text: "beta" },
      { value: "g", text: "gamma" }
    ]
  },
  methods: {
    change: (newValue) => {
      // perform actions with the selected text
      // "alpha", "beta", or "gamma"
      console.log(newValue);
    }
  }
});
<link href="https://cdn.jsdelivr.net/npm/@mdi/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a1c7cecfd5e1958fd9">[email protected]</a>/css/materialdesignicons.min.css" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c7b1b2a2b3aea1be87f5e9f5e9f5f7">[email protected]</a>/dist/vuetify.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/babel-polyfill/dist/polyfill.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b9cfccdcf98b97c1">[email protected]</a>/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="56202333223f302f16647864786466">[email protected]</a>/dist/vuetify.min.js"></script>
<div id="app">
  <v-app id="inspire">
    <v-container fluid>
      <label>The selected text is: {{state}}</label>
      <v-row align="center">
        <v-col cols="3">
          <v-select v-model="state" :items="states" @change="change" :text="selectedText"></v-select>
        </v-col>
      </v-row>
    </v-container>
  </v-app>
</div>

Answer №1

To ensure proper functionality, make sure to include the return-object prop within the <v-select> component.

new Vue({
  el: "#app",
  vuetify: new Vuetify(),
  data: {
    state: null,
    selectedText: "",
    states: [
      { value: "a", text: "alpha" },
      { value: "b", text: "beta" },
      { value: "g", text: "gamma" }
    ]
  },
  methods: {
    change: (newValue) => {
      // perform actions based on the selected text
      console.log(newValue.text);
    }
  }
});
<link href="https://cdn.jsdelivr.net/npm/@mdi/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aaccc5c4deea9e84d2">[email protected]</a>/css/materialdesignicons.min.css" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="21794a6a7d09687400">[email protected]</a>/dist/vuetify.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/babel-polyfill/dist/polyfill.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bbcdcedefb8995c3">[email protected]</a>/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="413734243528273801736f736f7371">[email protected]</a>/dist/vuetify.min.js"></script>
<div id="app">
  <v-app id="inspire">
    <v-container fluid>
      <label>my selected text is: {{state && state.text}}</label>
      <v-row align="center">
        <v-col cols="3">
          <v-select :items="states" v-model="state" @change="change" item-text="text" return-object></v-select>
        </v-col>
      </v-row>
    </v-container>
  </v-app>
</div>

Edit: To address this issue effectively, utilize the country code for identifying and setting the appropriate country object in the list.

Here's the solution implementation:

new Vue({
  el: "#app",
  vuetify: new Vuetify(),
  data: {
    country: "c",
    countries: [{
        code: "a",
        name: "Ameriga Fatela"
      },
      {
        code: "b",
        name: "Bolivia Grande"
      },
      {
        code: "c",
        name: "Comore Potentia"
      }
    ]
  },
  methods: {
    getCountryCode() {
      return "b"; // no 'c.name' available here!
    },
    change() {
      var newCode = this.getCountryCode();
      // Ensure objects are set when changing options 
      this.country = this.countries.filter(country => country.code === newCode)[0];
    }
  }
});
<link href="https://cdn.jsdelivr.net/npm/@mdi/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="84e2ebeaf0c4b0aafc">[email protected]</a>/css/materialdesignicons.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="47313222333a25030d08301c10341a011101191b">[email protected]</a>/dist/vuetify.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/babel-polyfill/dist/polyfill.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="97e1e2f2d7a5b9ef">[email protected]</a>/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="63151606161817113713171f">[email protected]</a>/dist/vuetify.min.js"></script>
<div id="app">
  <v-app>
    <v-container>
      <div>current code is &gt;{{country.code}}&lt;</div>
      <div>current name is &gt;{{country.name}}&lt;</div>
      <v-row>
        <v-col cols="12">
          <v-select v-model="country" :items="countries" item-text="name" item-value="code" return-object></v-select>
          <v-btn @click="change">change by script to 'b'</v-btn>
          </vcol>
      </v-row>
    </v-container>
  </v-app>
</div>

Answer №2

In your states objects, you have both the value and text properties. By changing value to key, v-select can recognize the change allowing you to access the text property using this.state. Here is an example:

new Vue({
  el: "#app",
  vuetify: new Vuetify(),
  data: {
    state: {},
    selectedText: "",
    states: [
      { key: "a", text: "alpha" },
      { key: "b", text: "beta" },
      { key: "g", text: "gamma" }
    ]
  },
  methods: {
    change: (newValue) => {
      // do something with the text
      // "alpha", "beta", or "gamma"
      console.log(newValue); // Returns text attribute instead of key
    }
  }
});
<div id="app">
  <v-app id="inspire">
    <v-container fluid>
      <label>My selected text is: {{state}}</label>
      <v-row align="center">
        <v-col cols="3">
          <v-select v-model="state" :items="states" @change="change"></v-select>
        </v-col>
      </v-row>
    </v-container>
  </v-app>
</div>

Answer №3

UPDATE: After exploring different options, I have discovered a more efficient solution using a computed property for the selected text, all without making changes to the existing code (view in FullPage mode to see the output correctly):

new Vue({
  el: "#app",
  vuetify: new Vuetify(),
  data: {
    countries: [
      { code: "a", name: "Alpha Land" },
      { code: "b", name: "Beta Isles" },
      { code: "c", name: "Gamma Republic" }
    ],
    country: "b"
  },
  methods: {
    getCountryCode() {
      return "c"; // there is no c.name here!
    },
    change() {
      this.country = this.getCountryCode();
    }
  },
  computed: {
    countryName() {
      return this.countries.find((c) => c.code === this.country).name;
    }
  }
});
<link href="https://cdn.jsdelivr.net/npm/@mdi/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d3b5bcbda793e7fdab">[email protected]</a>/css/materialdesignicons.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d4a2a1b1a0bdb2ad94e6fae6fae6e4">[email protected]</a>/dist/vuetify.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/babel-polyfill/dist/polyfill.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a9dfdccce99b87d1">[email protected]</a>/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="94e2e1f1e0fdf2edd4a6baa6baa6a4">[email protected]</a>/dist/vuetify.min.js"></script>
<div id="app">
  <v-app>
    <v-container>
      <div>current code is &gt;{{country}}&lt;</div>
      <div>current name is &gt;{{countryName}}&lt;</div>
      <v-row>
        <v-col cols="12">
          <v-select v-model="country" :items="countries" item-text="name" item-value="code"></v-select>
          <v-btn @click="change">change by script to '{{getCountryCode()}}'</v-btn>
          </vcol>
      </v-row>
    </v-container>
  </v-app>
</div>

Alternatively, you can check out Anurag Srivastava's suggestion to use return-object, as shown in this (Codepen link). However, this approach has some limitations when it comes to updating values through code:

new Vue({
  el: "#app",
  vuetify: new Vuetify(),
  data: {
    country: "c",
    countries: [
      { code: "a", name: "Alpha Land" },
      { code: "b", name: "Beta Isles" },
      { code: "c", name: "Gamma Republic" }
    ]
  },
  methods: {
    getCountryCode() {
      return "b"; 
    },
    change() {
      var newCode = this.getCountryCode();
      this.country = newCode;
    }
  }
});
<link href="https://cdn.jsdelivr.net/npm/@mdi/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="26404948526612085e">[email protected]</a>/css/materialdesignicons.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="06707363726f607f46342834283436">[email protected]</a>/dist/vuetify.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/babel-polyfill/dist/polyfill.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="463033230674683e">[email protected]</a>/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b5c3c0d0c1dcd3ccf5879b879b8785">[email protected]</a>/dist/vuetify.min.js"></script>
<div id="app">
  <v-app>
    <v-container>
      <div>current code is &gt;{{country.code}}&lt;</div>
      <div>current name is &gt;{{country.name}}&lt;</div>
      <v-row>
        <v-col cols="12">
          <v-select v-model="country" :items="countries" item-text="name" item-value="code" return-object></v-select>
          <v-btn @click="change">change by script to 'b'</v-btn>
          </vcol>
      </v-row>
    </v-container>
  </v-app>
</div>

In either case, the recalculating of the country name is necessary, which may not be optimal. Having to perform such a heavy operation each time can be time-consuming and inefficient....

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

Tips for relocating a CSS button

I have designed two buttons using css and I am looking to align them below the title "forecast customer activity". Due to extensive styling in css, the code might appear lengthy. Requesting assistance with a solution after reviewing the following code snip ...

Placing a material UI Radio button within a row cell on a table

Here is the current design snapshot: I am working with Material UI's radio button component and I want to ensure that each row in the table can be selected only once. Although I am able to select a single row using the <RadioButton> component, ...

Swap out a particular component during the testing phase

Currently, I am running tests on my React-Redux application using Jest. Within my API calls, I have integrated a fetch module called cross-fetch. However, I am looking to substitute this with fetch-mock. Take a look at my directory structure: Action.js i ...

The random string generator is selecting a unique string for both the server and client side

I am facing an issue with a component in Next.js (v14.2.1) where I need to display a random string while fetching data. Despite my attempts, I can't seem to maintain the same string on both server and client sides. Below is the code snippet I am curr ...

Passing Props in Material-UI v5xx with ReactJS: A Beginner's Guide

Struggling with the fact that useStyle() isn't functioning properly in my material-UI v5xx version, I found myself at a loss on how to pass props in this updated edition. In Material-UI v4, it was as simple as: const Navbar = () => { const [open ...

Vuetify's data table now displays the previous and next page buttons on the left side if the items-per-page option is hidden

I need help hiding the items-per-page choices in a table without affecting the next/previous functionality. To achieve this, I've set the following props: :footer-props="{ 'items-per-page-options':[10], &apo ...

Having trouble establishing a connection with the socket.io server on the local network

After successfully setting up communication between my nodeJS server and a vueJS app via socket.io on my main computer, I encountered a challenge. While running my node server and vue app in dev mode, the socket connection works when I access the app throu ...

Vue - The import statement cannot be used outside of a module context

I am currently working on developing a form that requires certain dependencies listed in the package.json file including vue, axios, and sweetalert. "dependencies": { "axios": "^0.19.0", "vue": "^2.6.10" ...

Issue with Vue causing Font Awesome updates to not display correctly

Is there a way to create a clickable "star" icon using font-awesome with bulma and switching between regular and solid styles (fas and far) in Vue? I have implemented the following component: <template> <span v-if="isStarred" class="icon star ...

Create a wait function that utilizes the promise method

I need to wait for the constructor() function, which contains an asynchronous method handled by Promise. My goal is to wait for two asynchronous methods within the constructor, and then wait for the constructor itself. However, my code is throwing an err ...

How can we optimize axios requests with lodash debounce?

Utilizing a state prop named network busy status to control elements in the UI. Due to the rapid changes in status, my spinner appears overly active. Is there a simple method, utilizing lodash _.debounce, to throttle this section of code? const instance ...

ReactJS error: Unable to access the setState property

As a newcomer to ReactJS, I have been facing some challenges. I recently familiarized myself with the ES6 syntax, and it claims that the following pieces of code are equivalent in meaning. 1. YTSearch({key: API_KEY, term: 'nba'}, function(vide ...

Extract several "documents" from one compilation

To easily convert my code into a single module using webpack, I can use the following method: { entry: path.join(__dirname, 'src/index.js'), output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', ...

What is the best way to send back a 401 error along with a personalized message?

I have encountered an AuthenticationException in my Web API while using the DoCdssLoginTests(...) method. When this exception is caught, I am currently returning a 401 error response, but I would like to include a custom message with it. Unfortunately, th ...

Error encountered while attempting to import the mongoose npm module into a React application

I'm encountering an issue in my React project where I am trying to include an npm module within a component. Here's an example: var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/test', {useNewUrlParser ...

Can you make two elements match each other at random?

Currently, I am working on developing a word guessing game where the displayed image should correspond with the word to be guessed. Unfortunately, I am encountering two major challenges in this process. Firstly, I am unable to get the image to display co ...

Enhancing the model using Sequelize JS

Currently, I am in the process of developing a basic API using Express and Sequelize JS. Recently, I encountered an issue while attempting to update a record with req.School, but no changes seemed to occur. Despite checking the code below thoroughly, I did ...

Switching between Login Form and Register Form in VueJS template

Recently, I attempted to switch between the 'Login Form' and 'Register Form' using code that I found on codepen Flat HTML5/CSS3 Login Form. While the code functioned properly on its own, when integrated into a Vue Template, the form fai ...

Arrange two divs with a full width of 100% next to each other

Is there a way to create two divs, each taking up 100% of the page width and side by side within a wrapper with overflow:hidden? How can I achieve this? I attempted using inline-block, but it didn't produce the desired outcome. Similarly, when I tri ...

To display a pattern with a series of alternating addition and subtraction operators, starting from -1 and ending at n, use JavaScript to iterate through the numbers and implement the pattern -1+

I've been struggling to locate the values despite numerous attempts. What steps can I take to resolve this issue? Below is my code snippet: var numVal = prompt(""); for (var i = 1; i <= numVal; i++) { if (i % 2 !== 0) { console.log("-"); ...