23

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.

2
  • If '.select-group' is your select element, then it will work, though you probably want to give it some text too: {value: "999", text: "999"}. Commented Mar 15, 2012 at 20:55
  • read more here - kvcodes.com/2016/10/… Commented Oct 16, 2016 at 4:42

5 Answers 5

43

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

$('<option>').val('999').text('999').appendTo('#groupid');
Sign up to request clarification or add additional context in comments.

Comments

18

Here is the solution..

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

Comments

11

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>

Comments

4

Here is alternative solution. this worked for me.

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

Comments

0

This worked for me:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.