如何使用 jQuery 向 DropDownList 添加选项?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/317095/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 08:57:09  来源:igfitidea点击:

How do I add options to a DropDownList using jQuery?

jqueryuser-interfacedrop-down-menu

提问by flesh

As the question says, how do I add a new option to a DropDownList using jQuery?

正如问题所说,如何使用 jQuery 向 DropDownList 添加新选项?

Thanks

谢谢

回答by nickf

Without using any extra plugins,

不使用任何额外的插件,

var myOptions = {
    val1 : 'text1',
    val2 : 'text2'
};
var mySelect = $('#mySelect');
$.each(myOptions, function(val, text) {
    mySelect.append(
        $('<option></option>').val(val).html(text)
    );
});

If you had lots of options, or this code needed to be run very frequently, then you should look into using a DocumentFragmentinstead of modifying the DOM many times unnecessarily. For only a handful of options, I'd say it's not worth it though.

如果您有很多选择,或者此代码需要非常频繁地运行,那么您应该考虑使用DocumentFragment而不是多次不必要地修改 DOM。对于少数选择,我会说这不值得。

------------------------------- Added --------------------------------

- - - - - - - - - - - - - - - - 添加 - - - - - - - - - --------------

DocumentFragmentis good option for speed enhancement, but we cannot create option element using document.createElement('option')since IE6 and IE7 are not supporting it.

DocumentFragment是提高速度的好选择,但document.createElement('option')由于 IE6 和 IE7 不支持它,我们无法使用它创建选项元素。

What we can do is, create a new select element and then append all options. Once loop is finished, append it to actual DOM object.

我们可以做的是,创建一个新的 select 元素,然后附加所有选项。循环完成后,将其附加到实际的 DOM 对象。

var myOptions = {
    val1 : 'text1',
    val2 : 'text2'
};
var _select = $('<select>');
$.each(myOptions, function(val, text) {
    _select.append(
            $('<option></option>').val(val).html(text)
        );
});
$('#mySelect').append(_select.html());

This way we'll modify DOM for only one time!

这样我们只会修改一次 DOM!

回答by Phrogz

With no plug-ins, this can be easier without using as much jQuery, instead going slightly more old-school:

在没有插件的情况下,这可以更轻松地使用 jQuery,而不是稍微老派一点:

var myOptions = {
    val1 : 'text1',
    val2 : 'text2'
};
$.each(myOptions, function(val, text) {
    $('#mySelect').append( new Option(text,val) );
});

If you want to specify whether or not the option a) is the default selected value, and b) should be selected now, you can pass in two more parameters:

如果要指定选项 a) 是否为默认选定值,而 b) 应立即选择,则可以再传入两个参数:

    var defaultSelected = false;
    var nowSelected     = true;
    $('#mySelect').append( new Option(text,val,defaultSelected,nowSelected) );

回答by cgreeno

With the plugin: jQuery Selection Box. You can do this:

使用插件:jQuery 选择框。你可以这样做:

var myOptions = {
        "Value 1" : "Text 1",
        "Value 2" : "Text 2",
        "Value 3" : "Text 3"
    }
    $("#myselect2").addOption(myOptions, false); 

回答by Har

You may want to clear your DropDown first $('#DropDownQuality').empty();

你可能想先清除你的 DropDown $('#DropDownQuality').empty();

I had my controller in MVC return a select list with only one item.

我让 MVC 中的控制器返回一个只有一项的选择列表。

$('#DropDownQuality').append(
        $('<option></option>').val(data[0].Value).html(data[0].Text));    

回答by Zakaria

Add item to list in the begining

在开始时将项目添加到列表

$("#ddlList").prepend('<option selected="selected" value="0"> Select </option>');

Add item to list in the end

最后将项目添加到列表中

$('<option value="6">Java Script</option>').appendTo("#ddlList");

Common Dropdown operation (Get, Set, Add, Remove) using jQuery

使用 jQuery 的常见下拉操作(Get、Set、Add、Remove)

回答by Marshal

Pease note @Phrogz's solution doesn't work in IE 8 while @nickf's works in all major browsers. Another approach is:

请注意@Phrogz 的解决方案在 IE 8 中不起作用,而@nickf 在所有主要浏览器中都有效。另一种方法是:

$.each(myOptions, function(val, text) {
    $("#mySelect").append($("&lt;option/&gt;").attr("value", val).text(text));
});

回答by Johan

And also, use .prepend() to add the option to the start of the options list. http://api.jquery.com/prepend/

此外,使用 .prepend() 将选项添加到选项列表的开头。 http://api.jquery.com/prepend/

回答by Jay

U can use direct

你可以直接使用

$"(.ddlClassName").Html("<option selected=\"selected\" value=\"1\">1</option><option value=\"2\">2</option>")

$"(.ddlClassName").Html("<option selected=\"selected\" value=\"1\">1</option><option value=\"2\">2</option>")

-> Here u can use direct string

-> 在这里你可以使用直接字符串

回答by chopss

using jquery you can use

使用 jquery 你可以使用

      this.$('select#myid').append('<option>newvalue</option>');

where "myid" is the idof the dropdown list and newvalueis the text that you want to insert..

其中“ myid”是下拉列表的ID,而newvalue是您要插入的文本。

回答by vapcguy

I needed to add as many options to dropdowns as there were dropdowns on my page. So I used it in this way:

我需要向下拉菜单中添加与页面上的下拉菜单一样多的选项。所以我是这样使用的:

function myAppender(obj, value, text){
    obj.append($('<option></option>').val(value).html(text));
}

$(document).ready(function() {
    var counter = 0;
    var builder = 0;
    // Get the number of dropdowns
    $('[id*="ddlPosition_"]').each(function() {
        counter++;
    });

    // Add the options for each dropdown
    $('[id*="ddlPosition_"]').each(function() {
        var myId = this.id.split('_')[1];

        // Add each option in a loop for the specific dropdown we are on
        for (var i=0; i<counter; i++) {
            myAppender($('[id*="ddlPosition_'+myId+'"]'), i, i+1);
        }
        $('[id*="ddlPosition_'+myId+'"]').val(builder);
        builder++;
    });
});

This dynamically set up dropdowns with values like 1 to n, and automatically selected the value for the order that dropdown was in (i.e. 2nd dropdown got "2" in the box, etc.).

这会动态设置下拉列表,其值为 1 到 n,并自动选择下拉列表所在顺序的值(即,第二个下拉列表在框中得到“2”等)。

It was ridiculous that I could not use thisor this.Objector $.objor anything like that in my 2nd .each(), though --- I actually had to get the specific ID of that object and then grab and pass that whole object to my function before it would append. Fortunately the ID of my dropdown was separated by a "_" and I could grab it. I don't feel I should have had to, but it kept giving me jQuery exceptions otherwise. Something others struggling with what I was might enjoy knowing.

但是,我不能在我的第二个中使用thisorthis.Object$.obj或类似的东西,这太荒谬了.each()——我实际上必须获得该对象的特定 ID,然后在它追加之前抓取整个对象并将其传递给我的函数。幸运的是,我的下拉列表的 ID 用“_”分隔,我可以抓住它。我不觉得我应该有,但它一直给我 jQuery 例外。其他人在为我的情况而苦苦挣扎时可能会喜欢知道。