如何使用 jQuery 更改 <select> 的选项?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1801499/
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 change options of <select> with jQuery?
提问by Mask
Suppose a list of options is available, how do you update the <select>
with new <option>
s?
假设有一个可用的选项列表,你如何<select>
用 new <option>
s更新?
回答by CMS
You can remove the existing options by using the empty
method, and then add your new options:
您可以使用该empty
方法删除现有选项,然后添加新选项:
var option = $('<option></option>').attr("value", "option value").text("Text");
$("#selectId").empty().append(option);
If you have your new options in an object you can:
如果您在对象中有新选项,您可以:
var newOptions = {"Option 1": "value1",
"Option 2": "value2",
"Option 3": "value3"
};
var $el = $("#selectId");
$el.empty(); // remove old options
$.each(newOptions, function(key,value) {
$el.append($("<option></option>")
.attr("value", value).text(key));
});
Edit:For removing the all the options but the first, you can use the :gt
selector, to get all the option
elements with index greater than zero and remove
them:
编辑:要删除除第一个之外的所有选项,您可以使用:gt
选择器来获取option
索引大于零的所有元素以及remove
它们:
$('#selectId option:gt(0)').remove(); // remove all options, but not the first
回答by ktusznio
I threw CMS's excellent answer into a quick jQuery extension:
我将 CMS 的出色回答放入了一个快速的 jQuery 扩展中:
(function($, window) {
$.fn.replaceOptions = function(options) {
var self, $option;
this.empty();
self = this;
$.each(options, function(index, option) {
$option = $("<option></option>")
.attr("value", option.value)
.text(option.text);
self.append($option);
});
};
})(jQuery, window);
It expects an array of objects which contain "text" and "value" keys. So usage is as follows:
它需要一个包含“文本”和“值”键的对象数组。所以用法如下:
var options = [
{text: "one", value: 1},
{text: "two", value: 2}
];
$("#foo").replaceOptions(options);
回答by rahul
$('#comboBx').append($("<option></option>").attr("value",key).text(value));
where comboBx is your combo box id.
其中 comboBx 是您的组合框 ID。
or you can append options as string to the already existing innerHTML and then assign to the select innerHTML.
或者您可以将选项作为字符串附加到已经存在的innerHTML,然后分配给选择的innerHTML。
Edit
编辑
If you need to keep the first option and remove all other then you can use
如果您需要保留第一个选项并删除所有其他选项,则可以使用
var firstOption = $("#cmb1 option:first-child");
$("#cmb1").empty().append(firstOption);
回答by Draco
For some odd reason this part
由于某些奇怪的原因,这部分
$el.empty(); // remove old options
from CMS solution didn't work for me, so instead of that I've simply used this
来自 CMS 解决方案对我不起作用,所以我只是简单地使用了它
el.html(' ');
And it's works. So my working code now looks like that:
它的作品。所以我的工作代码现在看起来像这样:
var newOptions = {
"Option 1":"option-1",
"Option 2":"option-2"
};
var $el = $('.selectClass');
$el.html(' ');
$.each(newOptions, function(key, value) {
$el.append($("<option></option>")
.attr("value", value).text(key));
});
回答by Yuri Gor
Removing and adding DOM element is slower than modification of existing one.
删除和添加 DOM 元素比修改现有元素要慢。
If your option sets have same length, you may do something like this:
如果您的选项集具有相同的长度,您可以执行以下操作:
$('#my-select option')
.each(function(index) {
$(this).text('someNewText').val('someNewValue');
});
In case your new option set has different length, you may delete/add empty options you really need, using some technique described above.
如果您的新选项集具有不同的长度,您可以使用上述某些技术删除/添加您真正需要的空选项。
回答by BERGUIGA Mohamed Amine
If for example your html code contain this code:
例如,如果您的 html 代码包含此代码:
<select id="selectId"><option>Test1</option><option>Test2</option></select>
In order to change the list of option inside your select, you can use this code bellow. when your name select named selectId.
为了更改选择中的选项列表,您可以使用以下代码。当您的名字选择 named selectId 时。
var option = $('<option></option>').attr("value", "option value").text("Text");
$("#selectId").html(option);
in this example above i change the old list of optionby only one new option.
在上面的这个例子中,我只用一个新选项更改了旧的选项列表。
回答by vierzehn
Does this help?
这有帮助吗?
$("#SelectName option[value='theValueOfOption']")[0].selected = true;
回答by Toto
Old school of doing things by hand has always been good for me.
老派的手工做事一直对我有好处。
Clean the select and leave the first option:
$('#your_select_id').find('option').remove() .end().append('<option value="0">Selec...</option>') .val('whatever');
If your data comes from a Json or whatever (just Concat the data):
var JSONObject = JSON.parse(data); newOptionsSelect = ''; for (var key in JSONObject) { if (JSONObject.hasOwnProperty(key)) { var newOptionsSelect = newOptionsSelect + '<option value="'+JSONObject[key]["value"]+'">'+JSONObject[key]["text"]+'</option>'; } } $('#your_select_id').append( newOptionsSelect );
My Json Objetc:
[{"value":1,"text":"Text 1"},{"value":2,"text":"Text 2"},{"value":3,"text":"Text 3"}]
清理选择并保留第一个选项:
$('#your_select_id').find('option').remove() .end().append('<option value="0">Selec...</option>') .val('whatever');
如果您的数据来自 Json 或其他任何内容(只需连接数据):
var JSONObject = JSON.parse(data); newOptionsSelect = ''; for (var key in JSONObject) { if (JSONObject.hasOwnProperty(key)) { var newOptionsSelect = newOptionsSelect + '<option value="'+JSONObject[key]["value"]+'">'+JSONObject[key]["text"]+'</option>'; } } $('#your_select_id').append( newOptionsSelect );
我的 Json Objetc:
[{"value":1,"text":"Text 1"},{"value":2,"text":"Text 2"},{"value":3,"text":"Text 3"}]
This solution is ideal for working with Ajax, and answers in Json from a database.
此解决方案非常适合使用 Ajax,并从数据库中使用 Json 进行回答。
回答by Roman Yakoviv
if we update <select>
constantly and we need to save previous value :
如果我们<select>
不断更新并且需要保存以前的值:
var newOptions = {
'Option 1':'value-1',
'Option 2':'value-2'
};
var $el = $('#select');
var prevValue = $el.val();
$el.empty();
$.each(newOptions, function(key, value) {
$el.append($('<option></option>').attr('value', value).text(key));
if (value === prevValue){
$el.val(value);
}
});
$el.trigger('change');