Javascript 如何使用vuejs获取所选选项的文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35748162/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the text of the selected option using vuejs?
提问by Hujjat Nazari
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.
我想获取所选选项输入的文本并将其显示在其他地方。我知道如何使用 jQuery 做到这一点,但我想知道我们如何使用 Vuejs 做到这一点。
Here is how we do in jQuery. I mean the text of Selected Option not the value.
这是我们在 jQuery 中的做法。我的意思是 Selected Option 的文本而不是值。
var mytext = $("#customerName option:selected").text();
Here is my HTML
这是我的 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 ?
现在我怎样才能在它下面显示选定的选项。像 Jan、Doe、Khan 吗?
回答by MrMojoRisin
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:
您可以将选定的值与具有两个属性的对象绑定,而不是仅将值定义为 id:值和文本。以产品为例:
<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":
然后就可以通过“value”访问文本了:
<h1>Value:
{{selected.id}}
</h1>
<h1>Text:
{{selected.text}}
</h1>
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>
回答by Ben Harvey
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:
在 Vue 方法中:
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.
但是您可以将其更改为 getinnerText
或其他任何内容。如果你使用 jQuery,你可以$(e).find(':selected').data('foo')
或者$(e).find(':selected').text()
更短一点。
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).
如果您将模型绑定到 select 元素,它只会返回值(如果设置)或选项的内容(如果没有设置值)(就像提交表单时那样)。
** EDIT **
** 编辑 **
I would say that the answer @MrMojoRisin gave is a much more elegant way of solving this.
我会说@MrMojoRisin 给出的答案是解决这个问题的更优雅的方法。
回答by Cohars
I guess your values should be in the JS. Then you can easily manipulate it. Simply by adding:
我猜你的价值观应该在 JS 中。然后你可以轻松地操纵它。只需添加:
data: {
selected: 0,
options: ['Jan', 'Doe', 'Khan']
}
Your markup will be cleaner:
您的标记将更清晰:
<select v-model="selected">
<option v-for="option in options" value="{{$index}}">{{option}}</option>
</select>
<br>
<span>Selected: {{options[selected]}}</span>
As th1rdey3 pointed out, you might want to use complex data and values couldn't simple be array's indexes. Still you can use and object key instead of the index. Here is the implementation.
正如 th1rdey3 指出的那样,您可能想要使用复杂的数据,而值不能简单地作为数组的索引。您仍然可以使用和对象键而不是索引。这是实现。
回答by Gorky
Assuming you have a customers
list and a selected customer
on your model, an example like below should work perfect:
假设您在模型上有一个customers
列表和一个选择customer
,下面的示例应该可以完美运行:
<select v-model="theCustomer">
<option :value="customer" v-for="customer in customers">{{customer.name}}</option>
</select>
<h1>{{theCustomer.title}} {{theCustomer.name}}</h1>
回答by th1rdey3
You can use Cohars style or you can use methods too. Data is kept in options
variable. The showText
method finds out the selected values text and returns it. One benefit is that you can save the text to another variable e.g. selectedText
您可以使用 Cohars 风格,也可以使用方法。数据保存在options
变量中。该showText
方法找出选定的值文本并返回它。一个好处是您可以将文本保存到另一个变量,例如selectedText
HTML:
HTML:
<div id='app'>
<select v-model="selected">
<option v-for="option in options" v-bind:value="option.value">
{{ option.text }}
</option>
</select>
<br>
<span>Selected: {{ showText(selected) }}</span>
</div>
JAVASCRIPT:
爪哇脚本:
var vm = new Vue({
el: '#app',
data: {
selected: 'A',
selectedText: '',
options: [{
text: 'One',
value: 'A'
}, {
text: 'Two',
value: 'B'
}, {
text: 'Three',
value: 'C'
}]
},
methods: {
showText: function(val) {
for (var i = 0; i < this.options.length; i++) {
if (this.options[i].value === val){
this.selectedText = this.options[i].text;
return this.options[i].text;
}
}
return '';
}
}
});
JSFiddle showing demo
JSFiddle 显示 demo
回答by Dexygen
I tried to use the following suggestion of MrMojoRisin's
我尝试使用 MrMojoRisin 的以下建议
v-bind:value="{ id: product.id, text: product.name }"
However for me this was resulting in that Object's toString()representation being assigned to value, i.e. [object Object]
但是对我来说,这导致对象的toString()表示被分配给值,即[object Object]
What I did instead in my code was to call JSON.stringifyon a similar object bound to the value:
我在代码中所做的是在绑定到该值的类似对象上调用JSON.stringify:
v-bind:value="JSON.stringify({id: lookup[lookupIdFields[detailsSection]], name: lookup.Name})"
Then of course I can convert it back to an object using JSON.parseand get the requisite id and name values from the result
然后我当然可以使用JSON.parse将它转换回一个对象并从结果中获取必要的 id 和 name 值
回答by Iannazzi
Outside of the template I access the name of the option like this:
在模板之外,我像这样访问选项的名称:
let option_name = this.options[event.target.options.selectedIndex].name
let option_name = this.options[event.target.options.selectedIndex].name
To do this take this approach to set up your template:
为此,请采用以下方法来设置模板:
Defined your options in an array like
[{"name":"Bar","value":1},{"name":"Baz","value":2}]
... etc
在数组中定义您的选项,例如
[{"name":"Bar","value":1},{"name":"Baz","value":2}]
... 等
Put your options in the data
function of the component
<script>export default {function data(){return { options }}}</script>
将您的选项放在data
组件的功能中
<script>export default {function data(){return { options }}}</script>
Load the options
in the template using v:for
:
<option v-for="option in options" v-bind:value="option.value">{{option.name}}</option>
options
使用v:for
以下命令加载模板:
<option v-for="option in options" v-bind:value="option.value">{{option.name}}</option>
Use @change="getOptionName"
on the select
element:
@change="getOptionName"
在select
元素上使用:
<select @change="getOptionName">
<select @change="getOptionName">
In your methods
get the name:
在你methods
的名字中:
getOptionName(event){ let option_name = this.options[event.target.options.selectedIndex].name }
getOptionName(event){ let option_name = this.options[event.target.options.selectedIndex].name }
Note in this case the object
options
in event.target.options
does not have anything to do with your data named options
... hopefully that will avoid confusion
请注意,在这种情况下,object
options
inevent.target.options
与您命名的数据没有任何关系options
......希望这会避免混淆
So a more advanced approach, but I believe when it is all set up correctly getting the name is not terrible, although It could be easier.
所以一个更高级的方法,但我相信当它正确设置时获得名称并不可怕,尽管它可能更容易。
回答by Ravi Ram
The below code worked to get the Text from the selected option. I added a v-on:change, which calls a function onChange()to the select element.
下面的代码用于从所选选项中获取文本。我添加了一个v-on:change,它调用一个函数onChange()到 select 元素。
methods:{
onChange: function(e){
var id = e.target.value;
var name = e.target.options[e.target.options.selectedIndex].text;
console.log('id ',id );
console.log('name ',name );
},
<select name="customerName" id="" v-on:change="onChangeSite($event)">
<option value="1">Jan</option>
<option value="2">Doe</option>
<option value="3">Khan</option>
</select>
回答by Bobby Knezevic
I think some of the answers here are a bit too complex, so I'd like to offer an easier solution. I'm only going to use an event handler in the example and leave out things like model binding, etc.
我认为这里的一些答案有点过于复杂,所以我想提供一个更简单的解决方案。我只会在示例中使用事件处理程序,而忽略模型绑定等内容。
<select @change="yourCustomMethod">
<option value="1">One</option>
<option value="2">Two</option>
</select>
Then in your Vue instance:
然后在你的 Vue 实例中:
...
methods: {
yourCustomMethod: function(event) {
var key = event.target.value, // example: 1
value = event.target.textContent; // example: One
}
}
...
回答by Mteuahasan
You can find it out in the Vue documentation here : http://vuejs.org/guide/forms.html#Select
您可以在此处的 Vue 文档中找到它:http: //vuejs.org/guide/forms.html#Select
Using v-model :
使用 v-model :
<select v-model="selected">
<option selected>A</option>
<option>B</option>
<option>C</option>
</select>
<br>
<span>Selected: {{ selected }}</span>
In your case, I guess you should do :
在你的情况下,我想你应该这样做:
<select name="customerName" id="" v-model="selected">
<option>Jan</option>
<option>Doe</option>
<option>Khan</option>
</select>
{{selected}}
Here is a working fiddle : https://jsfiddle.net/bqyfzbq2/
这是一个工作小提琴:https: //jsfiddle.net/bqyfzbq2/