如何使用 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

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

How to create options of a select element dynamically using jquery?

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 #groupidthen 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

If I understood correctly, below is what you need,

如果我理解正确,下面是你需要的,

$("<option></option>", 
     {value: "999", text: "Nine Ninety Nine"})
    .appendTo('.select-group');

DEMO

演示

Provided .select-groupis the selector for the <select></select>

提供的.select-group是选择器<select></select>

回答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));