如何使用jquery更新select的所有选项
我有一个地图对象,我放在我的控制器中的Spring ModelAndView
中,并转发到我的jsp视图以填充选择。 在第一次填充之后,我想用json对象替换用于填充select的map对象,我使用jquery AJAX检索并使用jQuery.parseJSON转换为对象。 我可以使用json对象的内容动态替换select的全部内容吗?
对于实际修改选项,你真的不需要jQuery。 您可以通过分配SELECT
框的options
属性的length
属性来清除旧选项,然后通过#add
和new Option()
添加新选项。
以下是使用jQuery进行XHR部分然后直接执行选项的几个示例:
从一个数组:
如果要从对象中的数组中绘制数据(在本例中,是由生成的对象上的属性options
标识的数组):
JSON:
{ "options": [ {"value": "New1", "text": "New Option 1"}, {"value": "New2", "text": "New Option 2"}, {"value": "New3", "text": "New Option 3"} ] }
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)); } } });
实例
直接来自一个对象:
如果您将对象的属性名称用作option
值,并将属性值用作选项文本:
JSON:
{ "new1": "New Option 1", "new2": "New Option 2", "new3": "New Option 3" }
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)); } } } });
实例
更新 :而不是
select.options.add(new Option(...));
你也可以这样做:
select.options[select.options.length] = new Option(...);
实例
...我认为实际上我倾向于使用options
数组式上的add
方法(我不是把它称为数组,因为它有一个方法, add
,数组没有;并且因为如果你使用push
,哪些数组有,它不起作用)。
我已经测试了两种方法
- IE6,7,8(Windows)
- Chrome(Linux和Windows)
- Firefox(Linux和Windows)
- Opera(Linux和Windows)
- Safari(Windows)
......而且两者都有效。 也许有Mac的人可以为我在OS X上试用Safari。
我会说两种方式得到非常非常好的支持。
$.ajax({ type: 'POST', url: getpolicytypeUrl , data: { sirket: companyname }, success: function (data) { $.each(data, function(index, element) { $('#policyshortname').append($('