David Willis
David Willis

Reputation: 1092

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

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:

 <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.

Upvotes: 23

Views: 73878

Answers (5)

Nadeemmnn Mohd
Nadeemmnn Mohd

Reputation: 724

Here is alternative solution. this worked for me.

$('#yourSelectBoxId').append("<option value='Saab'>Saab</option>");

Upvotes: 4

Titogelo
Titogelo

Reputation: 73

This worked for me:

$('#chat_list').append(new Option(this.subject, this.key_remote_jid));

Upvotes: 0

Vineet Kadkol
Vineet Kadkol

Reputation: 331

Here is the solution..

$('#yourSelectBoxId').append(new Option('optionName', 'optionValue'));

Upvotes: 18

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

If I understood correctly, below is what you need,

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

DEMO

Provided .select-group is the selector for the <select></select>

Upvotes: 11

elclanrs
elclanrs

Reputation: 94101

Where's .select-group? If you use id of #groupid then this should work just fine...

$('<option>').val('999').text('999').appendTo('#groupid');

Upvotes: 43

Related Questions