Javascript 更改 HTML Select 元素的选定选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7373058/
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
Changing the selected option of an HTML Select element
提问by llihttocs
In my HTML, I have a <select>
with three <option>
elements. I want to use jQuery to check each option's value against a Javascript var
. If one matches, I want to set the selected attribute of that option. How would I do that?
在我的 HTML 中,我有一个<select>
包含三个<option>
元素。我想使用 jQuery 来根据 Javascript 检查每个选项的值var
。如果匹配,我想设置该选项的 selected 属性。我该怎么做?
回答by kzh
Vanilla JavaScript
原生 JavaScript
Using plain old JavaScript:
使用普通的旧 JavaScript:
var val = "Fish";
var sel = document.getElementById('sel');
document.getElementById('btn').onclick = function() {
var opts = sel.options;
for (var opt, j = 0; opt = opts[j]; j++) {
if (opt.value == val) {
sel.selectedIndex = j;
break;
}
}
}
<select id="sel">
<option>Cat</option>
<option>Dog</option>
<option>Fish</option>
</select>
<button id="btn">Select Fish</button>
jQuery
jQuery
But if you reallywant to use jQuery:
但如果你真的想使用 jQuery:
var val = 'Fish';
$('#btn').on('click', function() {
$('#sel').val(val);
});
var val = 'Fish';
$('#btn').on('click', function() {
$('#sel').val(val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="sel">
<option>Cat</option>
<option>Dog</option>
<option>Fish</option>
</select>
<button id="btn">Select Fish</button>
jQuery - Using Value Attributes
jQuery - 使用值属性
In case your options have value attributes which differ from their text content and you want to select via text content:
如果您的选项具有与其文本内容不同的值属性,并且您想通过文本内容进行选择:
<select id="sel">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
<script>
var val = 'Fish';
$('#sel option:contains(' + val + ')').prop({selected: true});
</script>
Demo
演示
But if you do have the above set up and want to select by value using jQuery, you can do as before:
但是,如果您确实进行了上述设置并希望使用 jQuery 按值进行选择,则可以像以前一样:
var val = 3;
$('#sel').val(val);
Modern DOM
现代DOM
For the browsers that support document.querySelector
and the HTMLOptionElement::selected
property, this is a more succinct way of accomplishing this task:
对于支持document.querySelector
和HTMLOptionElement::selected
属性的浏览器,这是完成此任务的更简洁的方法:
var val = 3;
document.querySelector('#sel [value="' + val + '"]').selected = true;
Demo
演示
Knockout.js
淘汰赛.js
<select data-bind="value: val">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
<script>
var viewModel = {
val: ko.observable()
};
ko.applyBindings(viewModel);
viewModel.val(3);
</script>
Demo
演示
Polymer
聚合物
<template id="template" is="dom-bind">
<select value="{{ val }}">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
</template>
<script>
template.val = 3;
</script>
Demo
演示
Angular 2
角 2
Note: this has not been updated for the final stable release.
注意:这尚未针对最终稳定版本进行更新。
<app id="app">
<select [value]="val">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
</app>
<script>
var App = ng.Component({selector: 'app'})
.View({template: app.innerHTML})
.Class({constructor: function() {}});
ng.bootstrap(App).then(function(app) {
app._hostComponent.instance.val = 3;
});
</script>
Demo
演示
Vue 2
视图 2
<div id="app">
<select v-model="val">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
val: null,
},
mounted: function() {
this.val = 3;
}
});
</script>
Demo
演示
回答by Justin Buser
None of the examples using jquery in here are actually correct as they will leave the select displaying the first entry even though value has been changed.
此处使用 jquery 的示例实际上都不是正确的,因为即使值已更改,它们也会使选择显示第一个条目。
The right way to select Alaska and have the select show the right item as selected using:
选择阿拉斯加并让选择显示正确项目的正确方法是使用:
<select id="state">
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
</select>
With jquery would be:
使用 jquery 将是:
$('#state').val('AK').change();
回答by Ivin Raj
回答by Shef
Markup
标记
<select id="my_select">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>
jQuery
jQuery
var my_value = 2;
$('#my_select option').each(function(){
var $this = $(this); // cache this jQuery object to avoid overhead
if ($this.val() == my_value) { // if this option's value is equal to our value
$this.prop('selected', true); // select this option
return false; // break the loop, no need to look further
}
});
Demo
演示
回答by Manohar Reddy Poreddy
I want to change the select element's selected option's both value & textContent (what we see) to 'Mango'.
我想将选择元素的选定选项的值和文本内容(我们看到的)更改为“芒果”。
Simplest code that worked is below:
最简单的代码如下:
var newValue1 = 'Mango'
var selectElement = document.getElementById('myselectid');
selectElement.options[selectElement.selectedIndex].value = newValue1;
selectElement.options[selectElement.selectedIndex].textContent = newValue1;
Hope that helps someone. Best of luck.
Up vote if this helped you.
希望能帮助某人。祝你好运。
如果这对您有帮助,请投票。
回答by vol7ron
Selecting Option based on its value
var vals = [2,'c']; $('option').each(function(){ var $t = $(this); for (var n=vals.length; n--; ) if ($t.val() == vals[n]){ $t.prop('selected', true); return; } });
Selecting Option based on its text
var vals = ['Two','CCC']; // what we're looking for is different $('option').each(function(){ var $t = $(this); for (var n=vals.length; n--; ) if ($t.text() == vals[n]){ // method used is different $t.prop('selected', true); return; } });
根据其值选择选项
var vals = [2,'c']; $('option').each(function(){ var $t = $(this); for (var n=vals.length; n--; ) if ($t.val() == vals[n]){ $t.prop('selected', true); return; } });
根据文本选择选项
var vals = ['Two','CCC']; // what we're looking for is different $('option').each(function(){ var $t = $(this); for (var n=vals.length; n--; ) if ($t.text() == vals[n]){ // method used is different $t.prop('selected', true); return; } });
Supporting HTML
支持 HTML
<select>
<option value=""></option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select>
<option value=""></option>
<option value="a">AAA</option>
<option value="b">BBB</option>
<option value="c">CCC</option>
</select>
回答by Azmat Karim Khan
I used almost all of the answers posted here but not comfortable with that so i dig one step furter and found easy solution that fits my need and feel worth sharing with you guys.
Instead of iteration all over the options or using JQueryyou can do using core JSin simple steps:
我使用了这里发布的几乎所有答案,但对此并不满意,所以我进一步挖掘并找到了适合我需要的简单解决方案,并且觉得值得与你们分享。您可以通过简单的步骤使用核心JS,
而不是遍历所有选项或使用JQuery:
Example
例子
<select id="org_list">
<option value="23">IBM</option>
<option value="33">DELL</option>
<option value="25">SONY</option>
<option value="29">HP</option>
</select>
So you must know the value of the option to select.
所以你必须知道要选择的选项的值。
function selectOrganization(id){
org_list=document.getElementById('org_list');
org_list.selectedIndex=org_list.querySelector('option[value="'+id+'"]').index;
}
How to Use?
如何使用?
selectOrganization(25); //this will select SONY from option List
Your comments are welcome. :) AzmatHunzai.
欢迎您提出意见。:) AzmatHunzai。
回答by Salem
After a lot of searching I tried @kzh on select list where I only know option
inner text not value
attribute,
this code based on select answer I used it to change select option according to current page url
on this format
http://www.example.com/index.php?u=Steve
经过大量搜索后,我在选择列表上尝试了@kzh,其中我只知道option
内部文本而不是value
属性,此代码基于选择答案,我用它来根据url
此格式的
当前页面更改选择选项http://www.example.com/index.php?u=Steve
<select id="sel">
<option>Joe</option>
<option>Steve</option>
<option>Hyman</option>
</select>
<script>
var val = window.location.href.split('u=')[1]; // to filter ?u= query
var sel = document.getElementById('sel');
var opts = sel.options;
for(var opt, j = 0; opt = opts[j]; j++) {
// search are based on text inside option Attr
if(opt.text == val) {
sel.selectedIndex = j;
break;
}
}
</script>
This will keeps url
parameters shown as selected to make it more user friendly and the visitor knows what page or profile he is currently viewing .
这将保持url
参数显示为选定状态,使其更加用户友好,并且访问者知道他当前正在查看哪个页面或配置文件。
回答by Tristan Reid
Excellent answers - here's the D3 version for anyone looking:
很好的答案 - 这是适合任何人的 D3 版本:
<select id="sel">
<option>Cat</option>
<option>Dog</option>
<option>Fish</option>
</select>
<script>
d3.select('#sel').property('value', 'Fish');
</script>
回答by user7071893
I used this after updating a register and changed the state of request via ajax, then I do a query with the new state in the same script and put it in the select tag element new state to update the view.
我在更新寄存器并通过 ajax 更改请求状态后使用它,然后我在同一脚本中使用新状态进行查询,并将其放入 select 标记元素新状态以更新视图。
var objSel = document.getElementById("selectObj");
objSel.selectedIndex = elementSelected;
I hope this is useful.
我希望这是有用的。