Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

javascript - How to get the text of the selected option using vuejs?

I want to get the text of a selected option input and display it somewhere else. I know how to do it using jQuery but I want to know how can we do it using Vuejs.

Here is how we do in jQuery. I mean the text of Selected Option not the value.

var mytext = $("#customerName option:selected").text();

Here is my HTML

    <select name="customerName" id="">
         <option value="1">Jan</option>
         <option value="2">Doe</option>
         <option value="3">Khan</option>
   </select>

 {{customerName}}

Now how can I display the selected option under it. like Jan, Doe, Khan ?

question from:https://stackoverflow.com/questions/35748162/how-to-get-the-text-of-the-selected-option-using-vuejs

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Instead of define the value only as the id, you can bind the selected value with an object with two attributes: value and text. For example with products:

<div id="app">
   <select v-model="selected">
       <option v-for="product in products" v-bind:value="{ id: product.id, text: product.name }">
         {{ product.name }}
       </option>
   </select>
</div>

Then you can access to the text through the "value":

   <h1>Value:
     {{selected.id}}
   </h1>
   <h1>Text:
     {{selected.text}}
   </h1>

Working example

var app = new Vue({
  el: '#app',
  data: {
  selected: '',
    products: [
      {id: 1, name: 'A'},
      {id: 2, name: 'B'},
      {id: 3, name: 'C'}
    ]
  }
})
<div id="app">
   <select v-model="selected">
       <option v-for="product in products" v-bind:value="{ id: product.id, text: product.name }">{{ product.name }}
       </option>
   </select>
   <h1>Value:
   {{selected.id}}
   </h1>
   <h1>Text:
   {{selected.text}}
   </h1>
</div>
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...