如何使用 jquery 动态创建选择元素的选项?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9727930/
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 create options of a select element dynamically using jquery?
提问by David Willis
I need to create options of a select element dynamically via an ajax call. The number of options and their content will vary. This is how it looks prior to the ajax call:
我需要通过 ajax 调用动态创建选择元素的选项。选项的数量及其内容会有所不同。这是在 ajax 调用之前的样子:
<select name="groupid" style="width:100%;">
<option value="0" selected>(Please select an option)</option>
</select>
Here is one of my attempts to create an option element with a dummy value:
这是我尝试创建一个具有虚拟值的选项元素的尝试之一:
$("<option></option>", {value: "999"}).appendTo('.select-group');
But it adds it outside of select. I also don't know how to set the text within .
但它将它添加到选择之外。我也不知道如何在 .
Any ideas? I've seen some questions about populating existing select forms with a static number of existing options but not one like this.
有任何想法吗?我已经看到一些关于使用静态数量的现有选项填充现有选择表单的问题,但不是这样的。
Thanks.
谢谢。
回答by elclanrs
Where's .select-group
? If you use id of #groupid
then this should work just fine...
在哪儿.select-group
?如果您使用 id of#groupid
那么这应该可以正常工作...
$('<option>').val('999').text('999').appendTo('#groupid');
回答by Vineet Kadkol
Here is the solution..
这是解决方案..
$('#yourSelectBoxId').append(new Option('optionName', 'optionValue'));
回答by Selvakumar Arumugam
回答by Nadeemmnn Mohd
Here is alternative solution. this worked for me.
这是替代解决方案。这对我有用。
$('#yourSelectBoxId').append("<option value='Saab'>Saab</option>");
回答by Titogelo
This worked for me:
这对我有用:
$('#chat_list').append(new Option(this.subject, this.key_remote_jid));
$('#chat_list').append(new Option(this.subject, this.key_remote_jid));