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

Vue.js: Issue with updating list in parent component when using child component

I'm encountering an issue when utilizing a child component, the list fails to update based on a prop that is passed into it. When there are changes in the comments array data, the list does not reflect those updates if it uses the child component < ...

jqGrid display/hide columns options dialogue box

I am looking to implement a feature that allows users to toggle columns in my jqGrid. I came across a module for this purpose, but unfortunately, it is no longer supported in jqGrid 4.x. I have searched for a replacement module without success. Are there ...

Alternative Options for Playing Audio in Internet Explorer 8

I'm in the process of setting up a button that can both play and pause audio with a simple click. While this functionality is working smoothly in modern browsers like Google Chrome, I am facing compatibility issues with IE 8. Even after attempting to ...

Does JSX have an API that can handle self-closing tags, such as <br>, if they are not closed properly?

For my latest project, I've been working on a ReactJS component using JSX and it looks something like this: <script type="text/jsx"> var HelloWorld = React.createClass({ render: function() { return ( < ...

Implementing file change detection using view model in Angular

When using the input type file to open a file and trigger a function on change, you can do it like this: <input type="file" multiple="multiple" class="fileUpload" onchange="angular.element(this).scope().fileOpened(this)" /> The functi ...

Sorry, we encountered a snipcart issue: The public API key was not found. To fix this, please ensure that the attribute data-api-key is

I'm experiencing issues with loading Snipcart correctly. It's able to detect the API key on localhost and display the number of items in the cart, but when deployed to Netlify, it briefly shows the item count before displaying the error message: ...

Using v-bind to dynamically set styles in Vue.js

While utilizing v-bind:style to apply dynamic values, I encountered an issue where v-bind:style did not seem to work. However, in the console, I verified that v-bind:style was receiving the correct value (:style='{ color : red (or any other value) }&a ...

Exploring Nuxt's speed and efficiency with Lighthouse

Despite having simple code, I am puzzled by the low performance of my Nuxt web app in Lighthouse. You can check out my Nuxt web app deployed under the name hadicodes.com online. Here is a snippet from my nuxt.config: // Your nuxt.config settings here Th ...

Dependency management in ReactJS components

I am grappling with the optimal structure for a React component that is composed of other components. Let's look at the first example: <ColorSelect id="color" label={this.state.selectLabel} trigger={{ color: "lime", text: "Lime"}} onPropagateCli ...

Refreshing the page results in a 404 error when utilizing React Router

I am currently facing an issue with my web application setup. Back-End My back-end consists of a Node.js/express server that serves files in response to specific requests made to certain routes. Front-End On the front-end, I have React pages that commu ...

Handling routerLink exceptions in Angular 2, 4, and 5

In my app, I am working on catching routing exceptions. There are three ways in which a user can navigate: If the user types the address directly - this can be caught easily by using { path: '**', redirectTo: 'errorPage'} in the route ...

What is preventing the use of this promise syntax for sending expressions?

Typically, when using Promise syntax, the following code snippets will result in the same outcome: // This is Syntax A - it works properly getUser(id).then((user) => console.log(user) // Syntax B - also works fine getUser(id).then(console.log) However ...

Testing the ControllerAs syntax when dealing with forms in AngularJS

I am currently facing a situation with Angular that has left me quite puzzled. Controller function Controller () { // form used in template this.form ... } Template containing a form and utilizing the above controller Template <div ng-contr ...

Guide on managing firebase and webrtc tasks within a client-side component using Next.js 13

I developed a Next.js 13 application to share the camera feed using WebRTC and Firestore. Below is my page.tsx file where I am facing some challenges. I can't make this server-side because I'm using React hooks, and moving it to the client side i ...

jQuery GetJson fails to execute success function

I'm trying to use this code for an Ajax request to a JSON file: let formData = $("#myform").serialize(); $.getJSON("/files/data.json?" + formData, function(response){ alert(response); } ); However, there are no errors and the alert is n ...

What is the best way to divide my JavaScript objects among several files?

Currently, I'm in the process of organizing my JavaScript code into separate libraries. Within the net top-level-domain, I manage two companies - net.foxbomb and net.matogen. var net = { foxbomb : { 'MyObject' : function() { ...

Is there a way to access the original query string without it being automatically altered by the browser?

I'm currently encountering an issue with query strings. When I send an activation link via email, the link contains a query string including a user activation token. Here's an example of the link: http://localhost:3000/#/activation?activation_cod ...

Obtain the identifier of a div within nested HTML components by utilizing jQuery

How do I retrieve the id of the first div with the class: post, which is "367", using jquery in the given HTML code: <div id="own-posts"> <span class="title">Me</span> <div class="posts_container"> <div class="post"& ...

JQuery magic: Enhancing a div's visibility with animated mouseover effects

I'm trying to figure out how to animate a div on mouseover, specifically making it fade in/appear slowly. I believe I need to use the .animate function or something similar. $("#logo").mouseover(function() { $("#nav").css('visibility',&apos ...

Utilizing $asyncValidators in angularjs to implement error messages in the HTML: A guide

This is my first major form with validations and more. I've set up a Registration form and I'm utilizing ng-messages for validation. The issue arises when I have to check the username, whether it already exists in the JSON server we are using or ...