您如何使用 jquery 更新选择的所有选项

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

How do you update all options of a select with jquery

jqueryajaxjsonspring

提问by coder

I have a map object I am placing in a Spring ModelAndViewin my controller and forwarding to my jsp view to populate a select. After it populates the first time, I want to replace the map object used to populate the select with a json object I am retrieving using jquery AJAX and converting to an object using jQuery.parseJSON. Can I dynamically replace the entire contents of the select with the contents of the json object?

我有一个地图对象,我将其放置在ModelAndView控制器中的 Spring中并转发到我的 jsp 视图以填充选择。在第一次填充后,我想用一个 json 对象替换用于填充选择的地图对象,我使用 jquery AJAX 检索并使用 jQuery.parseJSON 转换为对象。我可以用json对象的内容动态替换select的全部内容吗?

回答by T.J. Crowder

For actually modifying the options, you don't really need jQuery. You can clear the old options by assigning to the lengthproperty of the optionsproperty of the SELECTbox, and then add new options via #addand new Option().

对于实际修改选项,您实际上并不需要 jQuery。您可以通过分配给框的length属性的options属性来清除旧选项SELECT,然后通过#add和添加新选项new Option()

Here are a couple of examples using jQuery for the XHR part and then doing the options directly:

下面是一些使用 jQuery 来处理 XHR 部分然后直接执行选项的示例:

From an array:

从数组:

If you're drawing the data from an array within the object (in this case, an array identified by the property optionson the resulting object):

如果您从对象内的数组中绘制数据(在这种情况下,是由options结果对象上的属性标识的数组):

JSON:

JSON:

{
  "options": [
    {"value": "New1", "text": "New Option 1"},
    {"value": "New2", "text": "New Option 2"},
    {"value": "New3", "text": "New Option 3"}
  ]
}

JavaScript:

JavaScript:

$.ajax({
  url: "http://jsbin.com/apici3",
  dataType: "json",
  success: function(data) {
    var options, index, select, option;

    // Get the raw DOM object for the select box
    select = document.getElementById('theSelect');

    // Clear the old options
    select.options.length = 0;

    // Load the new options
    options = data.options; // Or whatever source information you're working with
    for (index = 0; index < options.length; ++index) {
      option = options[index];
      select.options.add(new Option(option.text, option.value));
    }
  }
});

Live example

活生生的例子

Directly from an object:

直接从对象:

If you're using the object's property names as optionvalues, and the property values as the option text:

如果您使用对象的属性名称作为option值,并将属性值作为选项文本:

JSON:

JSON:

{
  "new1": "New Option 1",
  "new2": "New Option 2",
  "new3": "New Option 3"
}

JavaScript:

JavaScript:

$.ajax({
  url: "http://jsbin.com/apici3/2",
  dataType: "json",
  success: function(data) {
    var name, select, option;

    // Get the raw DOM object for the select box
    select = document.getElementById('theSelect');

    // Clear the old options
    select.options.length = 0;

    // Load the new options
    for (name in data) {
      if (data.hasOwnProperty(name)) {
        select.options.add(new Option(data[name], name));
      }
    }
  }
});

Live Example

现场示例



Update: Rather than

更新:而不是

select.options.add(new Option(...));

you can also do:

你也可以这样做:

select.options[select.options.length] = new Option(...);

Live example

活生生的例子

...which I think actually I would tend to use over the addmethod on the optionsarray-like-thing (I'm not calling it an array because it has a method, add, that arrays don't have; and because if you use push, which arrays dohave, it doesn't work).

...我认为实际上我倾向于addoptions类似数组的东西上使用方法(我不称它为数组,因为它有一个方法,add数组没有;并且因为如果你使用push,哪些数组确实有,它不起作用)。

I've tested both methods on

我已经测试了这两种方法

  • IE6,7,8 (Windows)
  • Chrome (Linux & Windows)
  • Firefox (Linux & Windows)
  • Opera (Linux & Windows)
  • Safari (Windows)
  • IE6,7,8 (Windows)
  • Chrome(Linux 和 Windows)
  • 火狐(Linux 和 Windows)
  • Opera(Linux 和 Windows)
  • Safari (Windows)

...and the both work. Perhaps someone with a Mac could try Safari on OS X for me.

...两者都有效。也许有 Mac 的人可以为我尝试 OS X 上的 Safari。

I'd say both ways are very, very well supported.

我想说这两种方式都得到了非常非常好的支持。

回答by Taner Deliloglu

       $.ajax({
                type: 'POST',
                url: getpolicytypeUrl ,
                data: { sirket: companyname },
                success: function (data) {

                    $.each(data, function(index, element) {
                        $('#policyshortname').append($('<option>', {
                            text: element.policyShortname
                        }));
                        $('#policyshortname').show(300);
                    });

                }
            });


        $('#policyshortname').html('refresh',true);