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 ?
We can get the selected option on change with Vue. js by setting @change to a method. We set v-model to the key reactive property bind the selected value attribute value to key . And we set @change to onChange($event) to call onChange with the change event object.
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>
I had this issue, where I needed to get a data attribute from a selected option, this is how I handled it:
<select @change="handleChange"> <option value="1" data-foo="bar123">Bar</option> <option value="2" data-foo="baz456">Baz</option> <option value="3" data-foo="fiz789">Fiz</option> </select>
and in the Vue methods:
methods: { handleChange(e) { if(e.target.options.selectedIndex > -1) { console.log(e.target.options[e.target.options.selectedIndex].dataset.foo) } } }
But you can change it to get innerText
or whatever. If you're using jQuery you can $(e).find(':selected').data('foo')
or $(e).find(':selected').text()
to be a bit shorter.
If you are binding a model to the select element, it will only return the value (if set) or the contents of the option if there is no value set (like it would on submitting a form).
** EDIT **
I would say that the answer @MrMojoRisin gave is a much more elegant way of solving this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With